Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify default value for a reference type

Tags:

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();

like image 535
Egor Pavlikhin Avatar asked Nov 01 '10 02:11

Egor Pavlikhin


People also ask

Do reference variables have default values in Java?

For type boolean , the default value is false . For all reference types (§4.3), the default value is null .

How can we set default value to the variable?

You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.


1 Answers

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(); }  
like image 191
Reed Copsey Avatar answered Oct 16 '22 05:10

Reed Copsey