1

Is there any background difference between two declarations:

var x = (string)null;

and

string x = null;

Will the runtime treat this declarations different ways? Will the compiler produce the same IL?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
user1016945
  • 877
  • 3
  • 22
  • 38

2 Answers2

3

Yes, it produces the same IL:

void Main()
{
    var x = (string)null;
    string y = null;
}

Produces (with optimizations turned off):

IL_0000:  nop         
IL_0001:  ldnull      
IL_0002:  stloc.0     // x
IL_0003:  ldnull      
IL_0004:  stloc.1     // y
IL_0005:  ret        

From the compilers perspective, you are assigning null to a string variable.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
1

In the first case the compiler does not know the type of x unless you specify it in the cast. The resulting IL codes are however the same in both cases.

György Kőszeg
  • 17,093
  • 6
  • 37
  • 65