Janos Nagy
Janos Nagy

Reputation: 27

How to cast an object to Type?

I want to cast an object to a type that a System.Type object defines. I only know the object and the Type as inputs, I can't add type parameters.

void Test()
{
    object obj = 3;
    Type type = typeof(int);

    int number = Cast(obj, type);

    Console.WriteLine($"{number}, {number.GetType()}"); // Should output "3, System.Int32"
}

// I can't change the inputs
??? Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
}

I guess there's a way to solve it using reflection but I couldn't find anything like this.

Upvotes: 2

Views: 5933

Answers (2)

Paweł Własiuk
Paweł Własiuk

Reputation: 135

It is possible to do it without changing the Cast method into a template. It needs to return dynamic type. To cast, you should use the method Convert.ChangeType.

//I can't change the inputs
dynamic Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
    return Convert.ChangeType(obj, type);
}

Upvotes: 6

Mohammed Sajid
Mohammed Sajid

Reputation: 4913

You can use ChangeType method :

1 - Cast method:

public static T Cast<T>(object obj)
{
    return (T)Convert.ChangeType(obj, typeof(T));
}

2 - Test method:

void Test()
{
    object obj = 3;

    int number = Cast<int>(obj);

    Console.WriteLine($"{number}, {number.GetType()}");
}

Result:

3, System.Int32

I hope you find this helpful.

Upvotes: 1

Related Questions