BornToCode
BornToCode

Reputation: 10213

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());
}

Upvotes: 5

Views: 11458

Answers (2)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

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));
}

Upvotes: 14

Adam Beck
Adam Beck

Reputation: 1271

public void My_Func(Object input, Type t)
{
    object test = new object();
    test = Convert.ChangeType(test, t);
    test = TypeDescriptor.GetConverter(t).ConvertFromString(input.ToString());
}

Upvotes: 1

Related Questions