Unfortunately, you cannot get the return type Nullable and support reference types using generics unless you specify that you want to return Nullable when making a call
public static T Get<T>(this DataRow row, string field) { if (row.IsNull(field)) return default(T); else return (T)row[field]; }
and when you call
var id = dr.Get<int?>("user_id");
I did not test this, just threw it here. Take a picture.
EDIT:
Alternatively, if you really wanted to convert value types to nullables and still be able to support link types, something like this might work
public static object GetDr<T>(this DataRow row, string field) { // might want to throw some type checking to make // sure row[field] is the same type as T if (typeof(T).IsValueType) { Type nullableType = typeof(Nullable<>).MakeGenericType(typeof(T)); if (row.IsNull(field)) return Activator.CreateInstance(nullableType); else return Activator.CreateInstance(nullableType, new[] { row[field] }); } else { return row[field]; } }
However for each use
var id = dr.Get<string>("username") as string; var id = (int?)dr.Get<int>("user_id");
This, however, will not be as effective as simply accepting a type with a null value in the parameters of a generic type.
Wes p source share