Initialize a null-cast variable to a variable data type
Is there any difference between the two?
There is no difference.
In ILSpy , the line List<string> list = (List<string>)null;
changes toList<string> list = null;
Is this a habit carried over from another programming language?
I can not tell. Maybe there was something different from null
before and then it was changed to null
.
List<string> list = (List<string>) Session["List"];
source to share
In this case, there is no practical difference, and both assignments will be compiled to the exact same MSIL opcodes. However, there is one case where casting zero matters, and when calling an overloaded method.
class A { }
class B { }
class C
{
public static void Foo( A value );
public static void Foo( B value );
}
It's just that the call is C.Foo( null );
ambiguous and the compiler can't reason about what you intend to call, but if you specify null: first C.Foo( (A)null );
, it is now clear that you want to call the first overload, but pass null to it instead of an instance A
.
source to share