My code is the following
int tmpCnt;
if (name == "Dude")
tmpCnt++;
Why is there an error Use of unassigned local variable tmpCnt
? I know I didn't explicitly initialize it but due to Default Value Table a value type is initialized with 0
anyways. The reference also reminds me:
Remember that using uninitialized variables in C# is not allowed.
But why do I have to do it explicitly if it's already done by default? Wouldn't it gain performance if I wouldn't have to do it? Just wondering...
Local variables are not automatically initialized. That only happens with instance-level variables.
You need to explicitly initialize local variables if you want them to be initialized. In this case, (as the linked documentation explains) either by setting the value of 0 or using the
new
operator.The code you've shown does indeed attempt to use the value of the variable
tmpCnt
before it is initialized to anything, and the compiler rightly warns about it.See this thread concerning uninitialized bools, but it should answer your question.
Local variables are not initialized unless you call their constructors (new) or assign them a value.
Default assignments apply to class members, but not to local variables. As Eric Lippert explained it in this answer, Microsoft could have initialized locals by default, but they choose not to do it because using an unassigned local is almost certainly a bug.
local variables don't have a default value.
They have to be definitely assigned before you use them. It reduces the chance of using a variable you think you've given a sensible value to, when actually it's got some default value.
While value types have default values and can not be null, they also need to be explicitly initialized in order to be used. You can think of these two rules as side by side rules. Value types can NOT be null==> the compiler guarantes that. If you ask how? the error message you got is the answer. Once you call their constructors, they got inialized with their default values.
The following categories of variables are classified as initially unassigned:
The following categories of variables are classified as initially assigned: