开发者

what's the difference between the default and default constructor

I have a class named A. What the differ开发者_Python百科ence between these two statements?

A a = new A();

A a = default(A);


This creates a new instance of the type A by calling the default, parameterless constructor:

A a = new A();

This assigns the default value for type A to the variable a and does not call any constructor at all:

A a = default(A);

The main difference is that the default value of a type is null for reference types and a zero-bit value for all value types (so default(int) would be 0, default(bool) would be false, etc.).


For value types there is no difference, since the default constructor of a value type is always equivalent to default(T). It just fills everything with 0, null, 0.0... In the default implementation of .net this just corresponds to filling everything in your variable with binary zero.

For reference types new T() calls the default constructor and returns a (usually) non null reference.
default(T) on the other hand is equivalent to null in this case.

default(T) is important because it represents a valid value of T, regardless whether T is a reference- or value-type. This is very useful in generic programming.
For example in functions like FirstOrDefault you need a valid value for your result in the case where the enumerable has no entries. And you just use default(T) for that since it's the only thing valid for every type.

Additionally calling the the default constructor on reference-types requires a generic constraint. And not every reference-type implements a default constructor. So you can't always use it.


The new keyword always signals memory allocation for reference types. No other construct actually creates space in memory for the data you are about to create. For value types, their memory is always pre-allocated when used in a function or procedure. The default keyword allows a generic type to return its default (uninitiazed) value, or null for reference types.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜