Specify default value for a reference type

前端 未结 2 1486
闹比i
闹比i 2020-12-10 01:19

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

相关标签:
2条回答
  • 2020-12-10 01:45

    Sorry, I'm not Jon Skeet...

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

    0 讨论(0)
  • 2020-12-10 01:50

    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();
    } 
    
    0 讨论(0)
提交回复
热议问题