Reputation: 86085
I have a class named A
. What the difference between these two statements?
A a = new A();
A a = default(A);
Upvotes: 11
Views: 1448
Reputation: 108800
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.
Upvotes: 2
Reputation: 29244
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.
Upvotes: 1
Reputation: 351516
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.).
Upvotes: 14