14

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?

nawfal
  • 70,104
  • 56
  • 326
  • 368
Jan Ohlson
  • 215
  • 4
  • 7

5 Answers5

13

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");
}
sloth
  • 99,095
  • 21
  • 171
  • 219
10

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

Will Dean
  • 39,055
  • 11
  • 90
  • 118
  • 1
    This answer is not altogether correct in its particulars, since the default value of a bool is not zero but false (to name just one value type whose default value is not zero; see [this article for a list](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/default-values). The canonical reference is [Default value expressions in the C# language specification](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#default-value-expressions). – Heretic Monkey Nov 11 '20 at 15:11
4

How about this:

var kid = kids.Where(k => k.Age < 10).SingleOrDefault() ?? new Kid();
Oliver
  • 43,366
  • 8
  • 94
  • 151
3

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

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
2

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());
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174