> 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<bool> etc is doing; it
> *looks* like it is converting an empty Nullable<bool> to object (which
> should yield null due to the boxing rules), then converting that null to a
> T, which we already know if Nullable<bool> (hence becoming another empty
> Nullable<bool>)- so we've got a complicated way of saying "null". In C#,
> 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<T>(object pReaderVar)
{
if (pReaderVar.Equals(DBNull.Value))
{
if (typeof(T) == typeof(string))
{
return (T)(object)"";
}
else if (typeof(T) == typeof(Nullable<bool>))
{
return (T)(object)new Nullable<bool>();
}
else
{
return default(T);
}
}
else
{
return (T)pReaderVar;
}
}
and yes, it returns null for a Nullable<bool>. I wonder why it's different
for VB.NET? Would be interesting to look at the MSIL.
Leon Mayne - 31 Mar 2008 14:01 GMT
> Would be interesting to look at the MSIL.
I just did this, and it looks like the VB version is using a different call
to unbox the object:
VB:
IL_00b9: box valuetype [mscorlib]System.Nullable`1<bool>
IL_00be: call !!0
[Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.Conversions::ToGenericParameter<!!0>(object)
C#:
IL_0066: box valuetype [mscorlib]System.Nullable`1<bool>
IL_006b: unbox.any !!T
So the Conversions::ToGenericParameter works but the direct unboxing
doesn't.
Leon Mayne - 31 Mar 2008 15:55 GMT
>> Would be interesting to look at the MSIL.
>
[quoted text clipped - 12 lines]
> So the Conversions::ToGenericParameter works but the direct unboxing
> doesn't.
Just tried it myself:
Return
Microsoft.VisualBasic.CompilerServices.Conversions.ToGenericParameter(Of
T)(New Nullable(Of Boolean))
Works fine in VB.NET, but not in C#:
return
Microsoft.VisualBasic.CompilerServices.Conversions.ToGenericParameter<T>(new
Nullable<Boolean>());
Something odd going on here!