I’m trying to write some code to convert data from a object type field (come from a DataSet) into it’s destination (typed) fields. I’m doing (trying at least) it using
dynamic conversion. It seems to work fine for strings, int, DateTime.
But it doesn’t work for unsigned types (ulong, uint). Below there’s a simple code that shows what I want to do. If you change the ul var type from ulong to int, it works fine.
Does anybody have a clue?
public class console
{
public static void CastIt<T>(object value, out T target)
{
target = (T) value;
}
public static void Main()
{
ulong ul;
string str;
int i;
DateTime dt;
object ul_o = (object) 2;
object str_o = (object) "This is a string";
object i_o = (object)1;
object dt_o = (object) DateTime.Now;
Console.WriteLine("Cast");
CastIt(ul_o, out ul);
CastIt(str_o, out str);
CastIt(i_o, out i);
CastIt(dt_o, out dt);
Console.WriteLine(ul);
Console.WriteLine(str);
Console.WriteLine(i);
Console.WriteLine(dt.ToString());
}
}
As Andrew says, the problem is that you can’t unbox from a boxed
inttoulong.Two options:
1) Box a
ulonginstead:or
2) Make
CastIt<T>useConvert.ChangeType:This is a bit smelly, but works with your example code. If you can use the first way in your real code, that would be better.