3

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?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
  • possible duplicate of [Cast a null into something?](http://stackoverflow.com/questions/10633946/cast-a-null-into-something) – celerno Oct 27 '14 at 18:12
  • 1
    I disagree, that is not a duplicate of my question. – Walter Stabosz Oct 27 '14 at 18:24
  • As the answers state, there is no difference in your lines of code. I believe it could be the effect of a refactoring tool as well, an example could be that originally `var` was used instead of explicit typing, and the refactoring tool just replace `var`. – flindeberg Oct 27 '14 at 19:16

4 Answers4

4

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"];
Habib
  • 219,104
  • 29
  • 407
  • 436
  • I was wondering if maybe C/C++ or Java required the casting of null. But I suppose it's possible that he replaced some code with the null. – Walter Stabosz Oct 27 '14 at 18:28
2

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.

1

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.

evilone
  • 22,410
  • 7
  • 80
  • 107
0

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;
Thomas Weller
  • 11,631
  • 3
  • 26
  • 34