How to convert any objects to Nullable
Simple extension method to convert in Nullable
public static class ObjectExtensions
{
public static Nullable<T> ToNullable<T>(this object input)
where T : struct
{
TypeConverter converter = TypeDescriptor
.GetConverter(typeof(T?));
return (T?)converter.ConvertFrom(input);
}
}
Written by Diego Dias
Related protips
2 Responses
When you are reading a DataReader for example, everything is object and cannot possibly make implicit conversion to nullable. So, this extension method can help you and your code still looks better.
var id = reader[columnIndex].ToNullable<int>();
over 1 year ago
·
Your example is an alternative to my, as mine is an alternative to your. I don't see no problem with extension methods to system.objects
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#.net
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#