user1649941
user1649941

Reputation: 123

Creating Object from Class name specified in string

I have a dropdownlist on a webpage which has list of all classnames , in C# code I need to instantiate object of selected items from dropdownlist and call method of it . All classes have similar methods .

 String sCalclationType = "N0059";
 var Calculator = Activator.CreateInstance("Calculator", sCalclationType ); 
 var count =  Calculator.DoCalculation();

I tried casting which shows "Cannot convert type 'System.Runtime.Remoting.ObjectHandle' to 'CypressDataImport.DiabetesHelper.NQF0059" , Also I need to cast to type which needs to be same as dropdown item so not sure how to do that .

//var calc = (N0059)Calculator; 

How do I handle this scenario ?

Upvotes: 1

Views: 1189

Answers (2)

Richard Vella
Richard Vella

Reputation: 186

You need to return the wrapped object returned by the Activator.CreateInstace() method.

To do that have a look at ObjectHandle.Unwrap on MSDN.

Please also make sure you are using the fully qualified name of your type as explained here.

Below is an example of usage:

Object obj = Activator.CreateInstance(System.Reflection.Assembly.GetExecutingAssembly().FullName, "CypressDataImport.DiabetesHelper.NQF0059.N0059").Unwrap();
N0059 calculator= (N0059)obj;

Upvotes: 1

Colin Smith
Colin Smith

Reputation: 12540

See here:

Try this:

String sCalclationType = "N0059";
ObjectHandle handle = Activator.CreateInstance("Calculator", sCalclationType ); 
var Calculator = (N0059)handle.Unwrap();
var count = Calculator.DoCalculation();

or

String sCalclationType = "N0059";
ObjectHandle handle = Activator.CreateInstance("Calculator", sCalclationType );
Object p = handle.Unwrap();
Type t = p.GetType();
MethodInfo method = t.GetMethod("DoCalculation");
var count = method.Invoke(p, null); 

Upvotes: 2

Related Questions