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
anyway. 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?
Use of unassigned local variable 'name' The C# compiler doesn't allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165.
In C and C++, local variables are not initialized by default. Uninitialized variables can contain any value, and their use leads to undefined behavior. Warning C4700 almost always indicates a bug that can cause unpredictable results or crashes in your program.
The CS0165 error is caused when a variable created within a method is not assigned with a value using the new keyword. The error CS0165 is resolved by assigning the local variable with a new instance of it's type or as a reference to a variable of the same type.
In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.
Local variables aren't initialized. You have to manually initialize them.
Members are initialized, for example:
public class X { private int _tmpCnt; // This WILL initialize to zero ... }
But local variables are not:
public static void SomeMethod() { int tmpCnt; // This is not initialized and must be assigned before used. ... }
So your code must be:
int tmpCnt = 0; if (name == "Dude") tmpCnt++;
So the long and the short of it is, members are initialized, locals are not. That is why you get the compiler error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With