Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize variable with null casted to variable's datatype

I ran across some code like this:

List<string> list = (List<string>)null;

Is there some reason the programmer didn't just initialize by:

List<string> list = null;

Is there a difference between the two?

Is this a habit that migrated from another programming language? Maybe C, C++, or Java?

like image 514
Walter Stabosz Avatar asked Apr 28 '26 17:04

Walter Stabosz


2 Answers

Is there a difference between the two?

No there is no difference.

In ILSpy, This line List<string> list = (List<string>)null; changes into List<string> list = null;

Is this a habit that migrated from another programming language?

Can't say. May be, earlier there was something different than null and then it was changed to null.

List<string> list = (List<string>) Session["List"];
like image 121
Habib Avatar answered May 01 '26 07:05

Habib


In this instance, there is no practical difference, and both assignments will compile down to exactly the same MSIL opcodes. However, there is one case where casting a null does make a difference, and that's when calling an overloaded method.

class A { }
class B { }

class C
{
    public static void Foo( A value );
    public static void Foo( B value );
}

Simply calling C.Foo( null ); is ambiguous, and the compiler can't reason about which you intend to invoke, but if you cast the null first: C.Foo( (A)null );, it's now clear that you mean to call the first overload, but pass it a null instead of an instance of A.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!