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();
For type boolean , the default value is false . For all reference types (§4.3), the default value is null .
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With