Re: Checking for DBNull with generics
am 31.03.2008 14:44:40 von Leon Mayne"Marc Gravell"
news:uz5%23tjxkIHA.3888@TK2MSFTNGP03.phx.gbl...
> Just for the record, string-compare on GetType is a nasty way to do
> things - surely comparing just the types [i.e. GetType(T) vs
> GetType(String) etc] would be cleaner? Granted: you can't do this in a
> switch... but If, ElseIf, etc should do.
Yes, that's why I was doing a string compare. Perhaps I should rewrite it as
you suggest for performance.
> I'm also a little confused as to what the Nullable
> *looks* like it is converting an empty Nullable
> should yield null due to the boxing rules), then converting that null to a
> T, which we already know if Nullable
> Nullable
> default(T) here would the same thing... I don't know what VB does, though.
I just checked this and it seems to work fine. It creates a new nullable(of
boolean) with no value, and HasValue = false. Is this different in C#?
*Leon checks
OK, I just tried:
public static T CheckDBNull
{
if (pReaderVar.Equals(DBNull.Value))
{
if (typeof(T) == typeof(string))
{
return (T)(object)"";
}
else if (typeof(T) == typeof(Nullable
{
return (T)(object)new Nullable
}
else
{
return default(T);
}
}
else
{
return (T)pReaderVar;
}
}
and yes, it returns null for a Nullable
for VB.NET? Would be interesting to look at the MSIL.