Babu James
Babu James

Reputation: 2843

Casting to Type from Type Object

Consider my code:

public class MyClass
{
//...
}

object ob = new MyClass();
Type t = ob.GetType();

With this information, I need to cast ob to MyClass at run-time. How do I do this?

Upvotes: 0

Views: 109

Answers (2)

CuccoChaser
CuccoChaser

Reputation: 1079

Assuming that MyClass is known at compile time:

object ob = new MyClass();

if (ob.GetType() != typeof(MyClass))
        MyClass convertedObject = (MyClass)ob;

Upvotes: 0

Honza Brestan
Honza Brestan

Reputation: 10947

Convert.ChangeType is what you are looking for.

// With ob and t from your example.
var myClassInstance = Convert.ChangeType(ob, t);

But as some people suggest, it would be good to know why do you need this in the first place. Chances are there's a smell in your approach to the problem and it can be done easier, without any type kung-fu.

Upvotes: 3

Related Questions