Nullable & reflection

L

Lloyd Dupont

I have written a class which automatically fills up an object's field from a
DbDataReader.
I'm trying to do some data type conversion before assigning the fields.

Unfortunately Convert.ChangetType((long) x, typeof(Nullable<long>)); throw
an InvalidCastException.

So I wonder, how could I, from the type information such as
Type aType = typeof(Nullable<long>);

and an object
object obj = 42L;

convert the object obj to the type of aType?
 
L

Lloyd Dupont

found a fix:
if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type tval = ft.GetGenericArguments()[0];
object val = Convert.ChangeType(o, tval);
return Activator.CreateInstance(ft, val);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top