Walter Stabosz
Walter Stabosz

Reputation: 7735

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?

Upvotes: 3

Views: 104

Answers (4)

user985916
user985916

Reputation:

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.

Upvotes: 2

evilone
evilone

Reputation: 22740

There's no difference between those two lines of code. It's matter of taste I think. Although if you use casting, you can remove the type from your variable, like this:

var list = (List<string>)null;

Without casting you can't do it.

Upvotes: 1

Thomas Weller
Thomas Weller

Reputation: 11717

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

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

Upvotes: 0

Habib
Habib

Reputation: 223287

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

Upvotes: 4

Related Questions