Nullable Types: How to String Format them?


C# 3 is pretty cool. Even though it has been around for a while, there are still tricks to be told to even the expert C# programmer.

Often enough, I usually see some code which would take in a Nullable<T>.Value and do some string formatting on the Nullable<T>.Value after doing all those compulsory checks on the Nullable<T>.Value.

So here is a snippet of code which expands on the following feature aspects of C# 3:

  • Extension methods
  • Generic type constraints
/*
Usage:

int? i = 5;
string v = i.ToString("0000");

*/

public static string ToString<T>(this T? target, string format)
    where T : struct, IFormattable
{
    return target.HasValue
               ? target.Value.ToString(format, CultureInfo.InvariantCulture)
               : null;
}

Well, happy programming! :)

blog comments powered by Disqus