I have been playing with generics and was hoping I could get some feedback or suggestions on a function I created to help handle reading null values from the DB. My main concern is in the if statement. Is there a better way to find out if T is a string ect.? Thanks.
public static T CheckNull<T>(object value)
{
if ((value != null) && value.Equals(DBNull.Value))
{
if (object.ReferenceEquals(typeof(T), typeof(String)))
value = string.Empty;
else if (object.ReferenceEquals(typeof(T), typeof(Boolean)))
value = false;
else
value = null;
}
return (T)value;
}
Regardless of
T‘s type, you can fall back todefault(T)which will provide the default value for the given type (,string.Empty0,false,null, etc…) :Edit:
default(string)does, however, returnnull.