Egor Pavlikhin
Egor Pavlikhin

Reputation: 17991

Specify default value for a reference type

As I understand default(object) where 'object' is any reference type always returns null, but can I specify what a default is? For instance, I want default(object) == new object();

Upvotes: 24

Views: 10646

Answers (3)

PotatoI9
PotatoI9

Reputation: 1

You can do something like this, it will call parameterless constructor

    public static T NewInstanceByType<T>(Type type) => (T)Activator.CreateInstance(type);

Upvotes: -1

Reed Copsey
Reed Copsey

Reputation: 564451

No. default(type) will always return the same thing - a "zero'ed out" version of that type. For a reference type, this is a handle to an object that is always set with a value of zero - which equates to null. For a value type, this is always the struct with all members set to zero.

There is no way to override this behavior - the language specification is designed this way.


Edit: As to your comment:

Just to be able to say FirstOrDefault() and never get a null.

I would not recommend this in any case. Users expect FirstOrDefault() to return null on failure. It would be better to write your own extension method:

static T FirstOrNewInstance<T>(this IEnumerable<T> sequence) where T : class, new()
{
     return sequence.FirstOrDefault() ?? new T();
} 

Upvotes: 35

Thomas Levesque
Thomas Levesque

Reputation: 292465

Sorry, I'm not Jon Skeet...

But anyway, the answer is "no you can't"

Upvotes: 8

Related Questions