C# Tips n Tricks: Coalesce

I’ve been using SQL for many years and find COALESCE to be extremely useful.  Recently I realized that if I could do the same functionality in C# it would be helpful, so I started to look.

For basic Coalesce functionality all you need to do is use the ?? operator.

string name = nameA ?? nameB ?? nameC ?? string.Empty;

For more advanced functionality I am planning to use the logic I found in the “Extending the C# Coalesce Operator” post on StackOverflow  to create an extension method that will allow the following code to work.

public class Bar
{
  public Bar Child { get; set; }
  public Foo Foo { get; set; }
}

Bar bar=new Bar { Child=new Bar { Foo=new Foo("value") } };

// prints "value":
Console.WriteLine(Coalesce.UntilNull(bar, b => b.Child, b => b.Foo, f => f.Value) ?? "null");

// prints "null":
Console.WriteLine(Coalesce.UntilNull(bar, b => b.Foo, f => f.Value) ?? "null");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s