C# features – question mark syntax
Some recent project work in C# unearthed a few grains of syntactic sugar which I thought deserved a quick post. Not necessarily because they are ground breaking discoveries, but more because I found it difficult to find information via the usual channels (google) and wanted to share. I think the poor information discovery is a result of said features being based on the question mark which is not an easy symbol to use for searches online.
Single Question Mark – nullable types
The single question mark syntax is somewhat obscure. Essentially it is short hand syntax for marking primitives as nullable. System.Nullable is a generic struct that is essentially a wrapper to signify nullability. This can be used as shown below:
// a nullable type for int int? thing = 12; // is syntactically equivalent to System.Nullable<int> otherThing = 12; // can be any valid int value OR null thing = -12; thing = null; // usage //y is set to zero int y = thing.GetValueOrDefault(); // but this will throw an exception as thing.HasValue == false y = thing.Value;
Double Question Mark – non null assignment precedence
This one is a little obscure but can be quite handy, it is very similar to certain assignment constructs in Perl as it allows one to use precedence to assign a variable from other potential variables and is a nice way to deal with default values.
String thing = null; String defaultThing = "nothing"; // standard trinary syntax String otherThing = (thing != null) ? thing : defaultThing; // syntactic sugar for the above String sugaredThing = thing ?? defaultThing; // can also chain things otherThing = null; // the first non-null value is the result of the assignment String anotherThing = thing ?? otherThing ?? defaultThing; // if all potentials are null, then the assignement is null) anotherThing = thing ?? otherThing;

November 27th, 2009 at 04:08:03
Thanks, just what I was looking for.