Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...