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?
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.
ChangeType method is gonna return type Object, not the type I wantAssuming that MyClass is known at compile time:
object ob = new MyClass(); if (ob.GetType() != typeof(MyClass)) MyClass convertedObject = (MyClass)ob; MyClass because he uses GetType.MyClass is known at compile time.
obto typeMyClassjust use(MyClass)ob. But is this what you're asking?