Why are reference types not initialized to null?

this. __curious_geek picture this. __curious_geek · Jan 6, 2010 · Viewed 7.8k times · Source

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;

Answer

mmx picture mmx · Jan 6, 2010

Only fields (variables declared at class level) are initialized automatically:

  • Value types are initialized to their default value.
  • Reference types are initialized to 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.