当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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?

网友答案:

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"];
网友答案:

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.

网友答案:

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.

网友答案:

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;
分享给朋友:
您可能感兴趣的文章:
随机阅读: