So I have been intrigued by the ?? operator, but have still been unable to use it. I usually think about it when I am doing something like:
var x = (someObje
I've been using it with App.Config stuff
string somethingsweet = ConfigurationManager.AppSettings["somesetting"] ?? "sugar";
I use it in working with methods that can return null under normal operation.
for example, lets say that I have a container class that has a Get method that returns null if the container doesn't contain a key (or maybe null is a valid association). Then I might do something like this:
string GetStringRep(object key) {
object o = container.Get(key) ?? "null";
return o.ToString();
}
clearly, these two sequences are equivalent:
foo = bar != null ? bar : baz;
foo = bar ?? baz;
The second is merely more terse.
I agree with you that the ?? operator is usually of limited use-- it's useful to provide a fall-back value if something is null, but isn't useful to prevent a Null Reference Exception in cases when you want to continue drilling down into properties or methods of a sometimes-null reference.
IMHO, what's needed much more than ?? is a "null-dereference" operator which allows you to chain long property and/or method chains together, e.g. a.b().c.d().e
without having to test each intermediate step for null-ness. The Groovy language has a Safe Navigation operator and it's very handy.
Luckily, it seems that the C# team is aware of this feature gap. See this connect.microsoft.com suggestion for the C# team to add a null-dereference operator to the C# language.
We get quite a number of requests for features similar to this one. The "?." version mentioned in the community discussion is closest to our hearts - it allows you to test for null at every "dot", and composes nicely with the existing ?? operator:
a?.b?.c ?? d
Meaning if any of a , a.b or a.b.c is null use d instead.
We are considering this for a future release, but it won't be in C# 4.0.
Thanks again,
Mads Torgersen, C# Language PM
If you also want this feature in C#, add your votes to the suggestion on the connect site! :-)
One workaround I use to get around the lack of this feature is an extension method like what's described in this blog post, to allow code like this:
string s = h.MetaData
.NullSafe(meta => meta.GetExtendedName())
.NullSafe(s => s.Trim().ToLower())
This code either returns h.MetaData.GetExtendedName().Trim().ToLower()
or it returns null if h, h.MetaData, or h.MetaData.GetExtendedName() is null. I've also extended this to check for null or empty strings, or null or empty collections. Here's code I use to define these extension methods:
public static class NullSafeExtensions
{
/// <summary>
/// Tests for null objects without re-computing values or assigning temporary variables. Similar to
/// Groovy's "safe-dereference" operator .? which returns null if the object is null, and de-references
/// if the object is not null.
/// </summary>
/// <typeparam name="TResult">resulting type of the expression</typeparam>
/// <typeparam name="TCheck">type of object to check for null</typeparam>
/// <param name="check">value to check for null</param>
/// <param name="valueIfNotNull">delegate to compute if check is not null</param>
/// <returns>null if check is null, the delegate's results otherwise</returns>
public static TResult NullSafe<TCheck, TResult>(this TCheck check, Func<TCheck, TResult> valueIfNotNull)
where TResult : class
where TCheck : class
{
return check == null ? null : valueIfNotNull(check);
}
/// <summary>
/// Tests for null/empty strings without re-computing values or assigning temporary variables
/// </summary>
/// <typeparam name="TResult">resulting type of the expression</typeparam>
/// <param name="check">value to check for null</param>
/// <param name="valueIfNotNullOrEmpty">delegate to compute non-null value</param>
/// <returns>null if check is null, the delegate's results otherwise</returns>
public static TResult CheckNullOrEmpty<TResult>(this string check, Func<string, TResult> valueIfNotNullOrEmpty)
where TResult : class
{
return string.IsNullOrEmpty(check) ? null : valueIfNotNullOrEmpty(check);
}
/// <summary>
/// Tests for null/empty collections without re-computing values or assigning temporary variables
/// </summary>
/// <typeparam name="TResult">resulting type of the expression</typeparam>
/// <typeparam name="TCheck">type of collection or array to check</typeparam>
/// <param name="check">value to check for null</param>
/// <param name="valueIfNotNullOrEmpty">delegate to compute non-null value</param>
/// <returns>null if check is null, the delegate's results otherwise</returns>
public static TResult CheckNullOrEmpty<TCheck, TResult>(this TCheck check, Func<TCheck, TResult> valueIfNotNullOrEmpty)
where TCheck : ICollection
where TResult : class
{
return (check == null || check.Count == 0) ? null : valueIfNotNullOrEmpty(check);
}
}
?? is a null check operator, in effect.
The reason your code gets into trouble is that if "someObject is null, then .someMember is a property on a null object. You'll have to check someObject for null first.
EDIT:
I should add that yes, I do find ?? to be very useful, especially in handling database input, especially from LINQ, but also in other cases. I use it heavily.
Just as an FYI, the ternary operator generates a different sequence of IL from the null coalescing operator. The first looks something like such:
// string s = null;
// string y = s != null ? s : "Default";
ldloc.0
brtrue.s notnull1
ldstr "Default"
br.s isnull1
notnull1: ldloc.0
isnull1: stloc.1
And the latter looks like such:
// y = s ?? "Default";
ldloc.0
dup
brtrue.s notnull2
pop
ldstr "Default"
notnull2: stloc.1
Based on this, I'd say the null coalescing operator is optimized for its purpose and is not just syntactic sugar.
The ??
operator is like the coalesce method in SQL, it gets you the first non-null value.
var result = value1 ?? value2 ?? value3 ?? value4 ?? defaultValue;