c# - Convert string to nullable type (int, double, etc...) - Stack Overflow

PHOTO EMBED

Mon Sep 25 2023 12:54:55 GMT+0000 (Coordinated Universal Time)

Saved by @rick_m #c#

public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
    Nullable<T> result = new Nullable<T>();
    try
    {
        if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
        {
            TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
            result = (T)conv.ConvertFrom(s);
        }
    }
    catch { } 
    return result;
}
content_copyCOPY

https://stackoverflow.com/questions/773078/convert-string-to-nullable-type-int-double-etc