1

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 ?

2 Answers 2

2

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

In 1st method you are doing (N0059) cast but we dont know the type of class . Second method will work fine I think . Is it somehow possible to use 1st method by using inheriting all classes from some main class ?
Yes. Create a base class that contains what all calculators should have...which I guess in your case is DoCalculation....and I guess a way to add terms.
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.