开发者

Should in generic class fields be initialized to their default values using default(T) or...?

With generics Default can be used to set a type parameter to its default value. This is clearly helpful given that a generic type does not know the actual placeholders up front a开发者_开发百科nd therefore cannot safely assume what the default value will be

When should in a generic class field be initialized via default(T) and when should we let the compiler set a field to its default value, or is it simply a matter of preference:

public class myType<T>
{
    public T _unkonwType1 =  default(T);
    public T _unknownType2;
}

thanx


No, fields never need to be initialized to their default values. (They will be so initialized regardless when the class is instantiated.)


The two statements in your question are identical. In the second statement an = default(T) is basically implied, and is done under-the-hood by the compiler.

However, if you explicitly call default(T), that will still get run, even though it is redundant.

How do I know, take a look at the IL generated for these two classes (even in Release builds):

public class MyClass1<T>
{
  public T Field;           
}

public class MyClass2<T>
{
  public T Field = default(T);
}

You'll see that the compiler does insert the call to default(T) like we asked it to, but of course that call will just return the initial value of the field anyway, so it's not needed.

So, to answer your question: you would take a (very slight) performance hit by explicitly calling default(T), but I don't believe it's going to affect very much in the long run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜