Check this code..
string str;
if (str.Contains("something.."))
{
}
Compiler throws this error for this code
Use of unassigned local variable 'str'
Why does a reference type is not initialized to null ?
Just want to know out of curiosity.
I'd also want to know what happens for code below. how does this assignment work ?
string str = null;
Only fields (variables declared at class level) are initialized automatically:
null
reference. What you are declaring is a "local variable" inside a method. Local variables are not automatically initialized regardless of being a value type or reference type.
I'd also want to know what happens for code below. how does this assignment work ?
This assignment initializes the local variable with null value with an ldnull
instruction followed by a stloc
instruction (in case it's not optimized out, of course) and more importantly, satisfies the compiler's data flow analysis rules for definite assignment. C# specification defines a concept called definite assignment that ensures a variable is assigned before first use.