开发者

Specify default value for a reference type

As I开发者_Python百科 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();


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


Sorry, I'm not Jon Skeet...

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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜