.Net Development27 Dec 2009 05:17 pm
Some Better ToString Methods for Nullable Types
When Microsoft added support for nullable types, why didn’t they add reasonable ToString() implementations as well? The idea that I cannot call someDate.ToString(“mm/dd/yyyy”) or someDecimal.ToString(“C”) and the like on Nullable<DateTime> and Nullable<decimal> respectively drives my bonkers. So I have written the following extension methods to restore my sanity.
using System; public static class NullableExtensionMethods { /// /// If null return "NULL" otherwise returns value.ToString(); /// public static string ToStringOrNullText(this T? value) where T : struct { return value.HasValue ? value.Value.ToString() : "NULL"; } /// /// If null return an empty string otherwise returns the value formated according to the format string; /// public static string ToString(this DateTime? value, string format) { return value.HasValue ? value.Value.ToString(format) : string.Empty; } /// /// If null return an empty string otherwise returns the value formated according to the format string; /// public static string ToString(this decimal? value, string format) { return value.HasValue ? value.Value.ToString(format) : string.Empty; } } |
Obviously, this approach can be extended to other types as well.