Initialize a null-cast variable to a variable data type

I came across some code:

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

      

Is there a reason the programmer didn't just initialize:

List<string> list = null;

      

Is there any difference between the two?

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

+3


source to share


4 answers


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"];

      

+4


source


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

.

+2


source


There is no difference between these two lines of code. I think it's a matter of taste. Although if you are using casting, you can remove this type from your variable, for example:

var list = (List<string>)null;

      

You can't do this without casting.

+1


source


No, in the above case, you don't need a cast. You only need this in a ternary expression:

return somecondition ? new List<string>() : (List<string>)null;

      

0


source







All Articles