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.
T : Nullable<T>doesn’t really make sense as a constraint – think about whatTwould have to be; it can’t be nullable of itself. You could have:but that would be somewhat obscure. I think it’s easier to make
Tthe non-nullable type and just refer toNullable<T>. I think you want this: