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();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…