0

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?

4
  • 1
    Millions of similar questions on SO ;) Why don't you know the type of your objects at compile time? Commented Dec 18, 2012 at 9:57
  • To cast ob to type MyClass just use (MyClass)ob. But is this what you're asking? Commented Dec 18, 2012 at 9:58
  • Please tell why you need to do this. Commented Dec 18, 2012 at 10:03
  • @DominicKexel, Why I need this: Simple, I have a list of class names from which I want to create object of them, one by one. Commented Dec 18, 2012 at 10:18

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This I have tried, but ChangeType method is gonna return type Object, not the type I want
0

Assuming that MyClass is known at compile time:

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

3 Comments

I assume that OP doesn't know at compile time that it's a MyClass because he uses GetType.
@TimSchmelter made the edit to check first if ob is a type of MyClass
Then @Blachshma's approach is better. But both of you are assuming that the type MyClass is known at compile time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.