What is the proper way to initialize a null variable in .NET? I’ve been told by one of my colleagues that hard defining of a variable to null is a slowdown.
int var1; // good practice
string s1; // good practice
int var2 = 0; // bad practice
string s2 = null; // bad practice
Is that correct?
Assuming you actually mean the default value instead of a null value, it could slow things down very, very slightly if you actually assign the value in the constructor instead of in the variable declaration. If it’s part of the variable declaration I would probably expect the JIT compiler to remove the unnecessary assignment, as the object’s memory is wiped on first initialization.
However, the chances of this being significant are absolutely tiny in either case.
Which do you find the more readable form? That’s much more important in the vast majority of cases.
EDIT: Note that for static fields at least, there are subtle cases where the two don’t behave the same way. Here’s an example – the Test1 and Test2 classes differ only in terms of whether the
ydeclaration has an assignment: