Can a Generic Method handle both Reference and Nullable Value types?

Posted by Adam Lassek on Stack Overflow See other posts from Stack Overflow or by Adam Lassek
Published on 2008-11-19T20:40:28Z Indexed on 2010/05/18 9:10 UTC
Read the original article Hit count: 259

Filed under:
|
|

I have a series of Extension methods to help with null-checking on IDataRecord objects, which I'm currently implementing like this:

public static int? GetNullableInt32(this IDataRecord dr, int ordinal)
{
    int? nullInt = null;
    return dr.IsDBNull(ordinal) ? nullInt : dr.GetInt32(ordinal);
}

public static int? GetNullableInt32(this IDataRecord dr, string fieldname)
{
    int ordinal = dr.GetOrdinal(fieldname);
    return dr.GetNullableInt32(ordinal);
}

and so on, for each type I need to deal with.

I'd like to reimplement these as a generic method, partly to reduce redundancy and partly to learn how to write generic methods in general.

I've written this:

public static Nullable<T> GetNullable<T>(this IDataRecord dr, int ordinal)
{
    Nullable<T> nullValue = null;
    return dr.IsDBNull(ordinal) ? nullValue : (Nullable<T>) dr.GetValue(ordinal);
}

which works as long as T is a value type, but if T is a reference type it won't.

This method would need to return either a Nullable type if T is a value type, and default(T) otherwise. How would I implement this behavior?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics