Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 353
Jan Ohlson Avatar asked Feb 23 '11 08:02

Jan Ohlson


People also ask

What does default t do?

Default represents default value of T parameter in generics intructions. In several cases, the default keyword is an absolute unknown and we think it's unnecessary or its functionality is null. There are many development moments with the generics classes where the default keyword can be useful.

What is default C#?

The default keyword returns the "default" or "empty" value for a variable of the requested type. For all reference types (defined with class , delegate , etc), this is null . For value types (defined with struct , enum , etc) it's an all-zeroes value (for example, int 0 , DateTime 0001-01-01 00:00:00 , etc).

What is the default value of a reference?

The default value of a reference type is null . It means that if a reference type is a static class member or an instance field and not assigned an initial value explicitly, it will be initialized automatically and assigned the value of null .

Which is used to represent default value of an empty expression?

C# default expression is a class (DefaultExpression) that is used to represent default value of an empty expression. It is a sub class of System. Linq.


1 Answers

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");
}
like image 150
sloth Avatar answered Oct 11 '22 16:10

sloth