Nick Chan Abdullah
Nick Chan Abdullah

Reputation: 375

creating instance of a type dynamically

Let's say I have this code:

object abc;
abc = typeof(myclass);

So, I'd like to do something like this

var newobject = GetTheValueTypeAndCreateTheInstance(abc);

and newobject is instance of myclass.

If I do abc = typeof(mycar), newobject is instance of mycar

Having abc variable, how do I create instance of myclass ? note that it could be any other class. Any help greatly appreciated !

Upvotes: 0

Views: 112

Answers (1)

Nick Chan Abdullah
Nick Chan Abdullah

Reputation: 375

I found a way to do it

object ABC = typeof(System.Text.StringBuilder);
dynamic _ABC = ABC;
var Instance = Activator.CreateInstance(_ABC.UnderlyingSystemType);

Upvotes: 2

Related Questions