How to change what default(T) returns in C#?

2019-01-11 23:20发布

I would like to change how default(T) behaves for certain classes. So instead of returning null for my reference types I would like to return a null object.

Kind of like

kids.Clear();
var kid = kids.Where(k => k.Age < 10).SingleOrDefault(); 

if (kid is NullKid)
{
  Console.Out.WriteLine("Jippeie");
}

Anyone know if this is at all possible?

5条回答
狗以群分
2楼-- · 2019-01-12 00:06

I don't think, it is possible. What you could do however, is to create your own extension method SingleOrCustomDefault or something like that.

查看更多
相关推荐>>
3楼-- · 2019-01-12 00:10

How about this:

var kid = kids.Where(k => k.Age < 10).SingleOrDefault() ?? new Kid();
查看更多
Fickle 薄情
4楼-- · 2019-01-12 00:17

Anyone know if this is at all possible?

It is simply not possible at all.

But maybe you want to use DefaultIfEmpty instead:

kids.Clear(); 
var kid = kids.Where(k => k.Age < 10).DefaultIfEmpty(NullKid).Single(); 

if (kid == NullKid)
{  
    Console.Out.WriteLine("Jippeie");
}
查看更多
该账号已被封号
5楼-- · 2019-01-12 00:24

You can't change default(T) - it's always null for reference types and zero for value types.

查看更多
狗以群分
6楼-- · 2019-01-12 00:25

I think you've already got the answer in your question: if/switch statement. Something like this:

if (T is Dog) return new Dog(); 
   //instead of return default(T) which is null when Dog is a class

You can make your own extension method like this:

public static T SingleOrSpecified<T>(this IEnumerable<T> source, Func<T,bool> predicate, T specified)
{
    //check parameters
    var result = source.Where(predicate);
    if (result.Count() == 0) return specified;
    return result.Single();   //will throw exception if more than 1 item
}

Usage:

var p = allProducts.SingleOrSpeficied(p => p.Name = "foo", new Product());
查看更多
登录 后发表回答