views:

206

answers:

1

I've seem to have gone down a rabbit hole. I would like to convert the data from ADO .NET datasets into a Nullable type. At first I assumed that a straight cast (int?) would do it. How naive I was. Wrong, badly wrong. Now I'm trying to write a generic converter but am getting hung up on the syntax. This is so 2005 - someone must have solved this problem already. Have you?

The hang up is that when I try to use a Nullable type as on constraint on the converter I get a syntax error:

public class NullableDBConversion
{
  public static T Convert<T>(object testValue) where T : Nullable<T>
  {
    if (testValue is DBNull)
    {
      return new Nullable<T>();
    }

    return new Nullable<T>((T)testValue);
  }
}

The goal have a single method using generics to do all conversions. Is this possible or do I have to write several.

+4  A: 

T : Nullable<T> doesn't really make sense as a constraint - think about what T would have to be; it can't be nullable of itself. You could have:

where T : Nullable<U> where U : struct

but that would be somewhat obscure. I think it's easier to make T the non-nullable type and just refer to Nullable<T>. I think you want this:

public static Nullable<T> Convert<T>(object testValue) where T : struct
{
    return testValue is DBNull ? null : new Nullable<T>((T)testValue);
}
Jon Skeet