Last Updated: December 26, 2018
·
1.425K
· diegodfsd

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);
    }
}

2 Responses
Add your response

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 ·