Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast an object to type passed to a function?

This doesn't compile, but what I'm trying to do is simply casting object to 't' which is passed to the function?

public void My_Func(Object input, Type t)
{
   (t)object ab = TypeDescriptor.GetConverter(t).ConvertFromString(input.ToString());
}
like image 717
BornToCode Avatar asked Jun 28 '12 14:06

BornToCode


2 Answers

You could do something like:

object ab = Convert.Changetype(input, t);

however, it looks like you want to use ab in a strongly-typed manner, which you can only do so by using generics:

public void My_Func<T>(Object input)
{
   T ab = (T)Convert.ChangeType(input, typeof(T));
}
like image 159
Eren Ersönmez Avatar answered Nov 17 '22 04:11

Eren Ersönmez


public void My_Func(Object input, Type t)
{
    object test = new object();
    test = Convert.ChangeType(test, t);
    test = TypeDescriptor.GetConverter(t).ConvertFromString(input.ToString());
}
like image 36
Adam Beck Avatar answered Nov 17 '22 04:11

Adam Beck