Monday, February 01, 2010

Nullable<T> and IFormattable

If you ever tried to format a nullable type you would soon realize that you cannot directly as Nullable<T> does not implement IFormattable and thus you only have object.ToString() available.

This is easily fixed using an extension method:

public static class NullableExtensions
{
public static string ToString<T>(
this Nullable<T> nullable,
string format,
IFormatProvider formatProvider)
where T : struct, IFormattable
{
if (!nullable.HasValue) return string.Empty;
T notNull = nullable.Value;
return notNull.ToString(format, formatProvider);
}
}


and you can use it e.g. like so:



            DateTime? foo = null;
...
foo.ToString("t", CultureInfo.CurrentCulture);

No comments: