Any difference between the following two
1) A a;
A a = null;
Is there any di开发者_运维知识库fference?
For a local variable, absolutely - the first isn't definitely assigned, the second is. For example:
void DoesntCompile()
{
A a;
string x = a.ToString(); // Can't use a - it's not definitely assigned
}
void CompilesButGoesBang()
{
A a = null;
string x = a.ToString(); // Throws a NullReferenceException
}
For an field (static or instance), if A
is a reference type, it probably doesn't make any difference. I could write a program to demonstrate a difference in the case where it's a static variable, but it would rely on executing the static type initializer twice using reflection... nasty.
If you could give more context about why you're asking, that would really help.
In C#, variables default according to the rules listed here.
The main difference between those two is that for case 2 the variable can be considered "definitely assigned". Depending on how the variable is going to be used, it may need to be definitely assigned before the compiler will allow certain operations. Please see this note on definite assignment.
精彩评论