Consider the following code开发者_C百科 snippet from .NET 4.0 library:
private T[] array;
private static T[] emptyArray;
private int size;
private int version;
static Stack()
{
Stack<T>.emptyArray = new T[0];
}
public Stack()
{
array = Stack<T>.emptyArray;
size = 0;
version = 0;
}
Is there any reason behind initializing value type private fields to default values (size
and version
in the example above) explicitely other than coding standards of the company?
No, there is not, at least not a technical reason. Perhaps in some cases one might do that to make a point, for example if you have a counter variable of some sort and you want to make clear it starts from zero. But I think even this is a bit questionable.
I think it's usually a good practice to initialize collections, primarily because it ensures the developer that he does not need to initialize anything on usage, and just assumes the variable has been initialized.
public class Store
{
public Store()
{
// Ready to go!
Products = new List<Product>();
}
public string Id {get;set;}
public IList<Product> Products {get;set;}
}
You jump through the hoopla of having to check if the collection has been initialized, if not do so, else... yawn
IMO, there is no need or benefit to initialize private variables to their default values (unless it's part of standards).
Edit: few times, it may make sense (as it improves code readability) - for example
public const OP_GET = 0;
public const OP_ADD = 1;
...
private int operation = OP_GET;
If they are primitive data type you don't need to initialize they will always take their default value
int,long etc. will always have its default value as 0 while bool will have false etc.
if it is a reference type you may have to initialize so that they have some default value (according to your logic) and avoid Null Reference errors
精彩评论