How to fill in constructor parameters in runtime? - c#

I want to create an instance of a type, but I don't know the type until runtime.
How can I get the constructor's required parameters to display them to the user in a WPF-window?
is there something like Properties Window in Visual Studio to be used?

Have a look at the ParameterInfo objects which can be obtained from the reflected type:
Type type = typeof(T);
ConstructorInfo[] constructors = type.GetConstructors();
// take one, for example the first:
var ctor = constructors.FirstOrDefault();
if (ctor != null)
{
ParameterInfo[] params = ctor.GetParameters();
foreach(var param in params)
{
Console.WriteLine(string.Format("Name {0}, Type {1}",
param.Name,
param.ParameterType.Name));
}
}

Here is the search - http://www.bing.com/search?q=c%23+reflection+constructor+parameters - top answer is ConstructorInfo with sample:
public class MyClass1
{
public MyClass1(int i){}
public static void Main()
{
try
{
Type myType = typeof(MyClass1);
Type[] types = new Type[1];
types[0] = typeof(int);
// Get the public instance constructor that takes an integer parameter.
ConstructorInfo constructorInfoObj = myType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public, null,
CallingConventions.HasThis, types, null);
if(constructorInfoObj != null)
{
Console.WriteLine("The constructor of MyClass1 that is a public " +
"instance method and takes an integer as a parameter is: ");
Console.WriteLine(constructorInfoObj.ToString());
}
else
{
Console.WriteLine("The constructor of MyClass1 that is a public instance " +
"method and takes an integer as a parameter is not available.");
}
}
catch(Exception e) // stripped out the rest of excepitions...
{
Console.WriteLine("Exception: " + e.Message);
}
}
}

Related

How to use Activator.CreateInstance to reflect a type whose constructor parameter differs only by ref

How to use reflection to create an instance of the type below while calling a specific constructor? Checked all the overloads of Activator.CreateInstance but don't think there is a match for this.
In the example below, I want x to be doubled after an instance of SomeType is created, namely, I want the constructor taking the ref int version to be called.
Also, how does MS define the 'best match' algorithm for CreatInstance method?
internal sealed class SomeType
{
//consturctor with non-reference parameter
public SomeType(int x)
{
x *= 3;
}
//constructor with reference parameter
public SomeType(ref int x)
{
x *= 2;
}
}
class Program
{
private static void main()
{
var param = new object[] {4}; // constructor parameter
Console.WriteLine("Param Before consturctor called: " + param[0]);
Object instance = Activator.CreateInstance(typeof(SomeType), param);
Console.WriteLine("Param after constuctor called: " + param[0]);
}
}
In order to match the ref int x parameter, you can create an instance using Type.GetConstructor and passing it an System.Int32& as a parameter:
var ctor = typeof(SomeType).GetConstructor(new[] { Type.GetType("System.Int32&") });
var constructorParameters = new object[] { 1 };
SomeType someType = (SomeType)ctor.Invoke(constructorParameters);
Edit:
As #mikez suggested, it is even better to use typeof(int).MakeByRefType() instead of System.Int32&:
var ctor = typeof(SomeType).GetConstructor(new[] { typeof(int).MakeByRefType(); });
var constructorParameters = new object[] { 1 };
SomeType someType = (SomeType)ctor.Invoke(constructorParameters);

Add a property at runtime to an existing object by using propertyBuilder

An object has some properties , now at runtime -- when a condition is met .. I want to add new properties to this object .
"DynamicObject" cant be ustilised since i wont be knowing the property Names beforehand .
I came acroos PropertyBuilder http://msdn.microsoft.com/en-us/library/system.reflection.emit.propertybuilder.aspx
But i cant find help regarding how to use the propertBuilder for adding properties to an existing object of a defined-existing class.
You cannot add real (reflection) properties to an object or type at runtime.
If the context here is data-binding, then you can all artificial properties, by implementing one or more of ICustomTypeDescriptor, TypeDescriptionProvider, TypeConverter, ITypedList - and providing your own PropertyDescriptors for the extra properties.
ICustomTypeDescriptor is per-object and tied to that object
TypeDescriptionProvider is per-object or per-type, and is separate to the object
TypeConverter is per-type and is used in particular by PropertyGrid
ITypedList is used by a list (IList) to describe the properties of the child objects
Example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
FooConverter.AddProperty("Time", typeof(DateTime));
FooConverter.AddProperty("Age", typeof(int));
using (var grid = new PropertyGrid { Dock = DockStyle.Fill, SelectedObject = new Foo() })
using (var form = new Form { Controls = { grid } })
{
Application.Run(form);
}
}
}
class FooConverter : ExpandableObjectConverter
{
private static readonly List<Tuple<string, Type>> customProps = new List<Tuple<string, Type>>();
public static void AddProperty(string name, Type type)
{
lock (customProps) customProps.Add(Tuple.Create(name, type));
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes)
{
var orig = base.GetProperties(context, value, attributes);
lock(customProps)
{
if(customProps.Count == 0) return orig;
PropertyDescriptor[] props = new PropertyDescriptor[orig.Count + customProps.Count];
orig.CopyTo(props, 0);
int i = orig.Count;
foreach (var prop in customProps)
{
props[i++] = new SimpleDescriptor(prop.Item1, prop.Item2);
}
return new PropertyDescriptorCollection(props);
}
}
class SimpleDescriptor : PropertyDescriptor
{
private readonly Type type;
public SimpleDescriptor(string name, Type type)
: base(name, new Attribute[0])
{
this.type = type;
}
public override Type PropertyType { get { return type;} }
public override bool SupportsChangeEvents { get { return false; } }
public override void ResetValue(object component) { SetValue(component, null); }
public override bool CanResetValue(object component) { return true; }
public override bool ShouldSerializeValue(object component) { return GetValue(component) != null; }
public override bool IsReadOnly { get { return false; } }
public override Type ComponentType { get { return typeof(Foo); } }
public override object GetValue(object component) { return ((Foo)component).GetExtraValue(Name); }
public override void SetValue(object component, object value) { ((Foo)component).SetExtraValue(Name, value); }
public override string Category { get { return "Extra values"; } }
}
}
[TypeConverter(typeof(FooConverter))]
public class Foo
{
Dictionary<string, object> extraValues;
internal object GetExtraValue(string name)
{
object value;
if (extraValues == null || !extraValues.TryGetValue(name, out value)) value = null;
return value;
}
internal void SetExtraValue(string name, object value)
{
if (extraValues == null && value != null) extraValues = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);
if (value == null) extraValues.Remove(name);
else extraValues[name] = value;
}
public int Id { get; set; }
public string Name { get; set; }
}
Check this Address
https://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes(v=vs.110).aspx
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
class EmitWriteLineDemo {
public static Type CreateDynamicType() {
Type[] ctorParams = new Type[] {typeof(int),
typeof(int)};
AppDomain myDomain = Thread.GetDomain();
AssemblyName myAsmName = new AssemblyName();
myAsmName.Name = "MyDynamicAssembly";
AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
myAsmName,
AssemblyBuilderAccess.Run);
ModuleBuilder pointModule = myAsmBuilder.DefineDynamicModule("PointModule",
"Point.dll");
TypeBuilder pointTypeBld = pointModule.DefineType("Point",
TypeAttributes.Public);
FieldBuilder xField = pointTypeBld.DefineField("x", typeof(int),
FieldAttributes.Public);
FieldBuilder yField = pointTypeBld.DefineField("y", typeof(int),
FieldAttributes.Public);
Type objType = Type.GetType("System.Object");
ConstructorInfo objCtor = objType.GetConstructor(new Type[0]);
ConstructorBuilder pointCtor = pointTypeBld.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
ctorParams);
ILGenerator ctorIL = pointCtor.GetILGenerator();
// First, you build the constructor.
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Call, objCtor);
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Ldarg_1);
ctorIL.Emit(OpCodes.Stfld, xField);
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Ldarg_2);
ctorIL.Emit(OpCodes.Stfld, yField);
ctorIL.Emit(OpCodes.Ret);
// Now, you'll build a method to output some information on the
// inside your dynamic class. This method will have the following
// definition in C#:
// public void WritePoint()
MethodBuilder writeStrMthd = pointTypeBld.DefineMethod(
"WritePoint",
MethodAttributes.Public,
typeof(void),
null);
ILGenerator writeStrIL = writeStrMthd.GetILGenerator();
// The below ILGenerator created demonstrates a few ways to create
// string output through STDIN.
// ILGenerator.EmitWriteLine(string) will generate a ldstr and a
// call to WriteLine for you.
writeStrIL.EmitWriteLine("The value of this current instance is:");
// Here, you will do the hard work yourself. First, you need to create
// the string we will be passing and obtain the correct WriteLine overload
// for said string. In the below case, you are substituting in two values,
// so the chosen overload is Console.WriteLine(string, object, object).
String inStr = "({0}, {1})";
Type[] wlParams = new Type[] {typeof(string),
typeof(object),
typeof(object)};
// We need the MethodInfo to pass into EmitCall later.
MethodInfo writeLineMI = typeof(Console).GetMethod(
"WriteLine",
wlParams);
// Push the string with the substitutions onto the stack.
// This is the first argument for WriteLine - the string one.
writeStrIL.Emit(OpCodes.Ldstr, inStr);
// Since the second argument is an object, and it corresponds to
// to the substitution for the value of our integer field, you
// need to box that field to an object. First, push a reference
// to the current instance, and then push the value stored in
// field 'x'. We need the reference to the current instance (stored
// in local argument index 0) so Ldfld can load from the correct
// instance (this one).
writeStrIL.Emit(OpCodes.Ldarg_0);
writeStrIL.Emit(OpCodes.Ldfld, xField);
// Now, we execute the box opcode, which pops the value of field 'x',
// returning a reference to the integer value boxed as an object.
writeStrIL.Emit(OpCodes.Box, typeof(int));
// Atop the stack, you'll find our string inStr, followed by a reference
// to the boxed value of 'x'. Now, you need to likewise box field 'y'.
writeStrIL.Emit(OpCodes.Ldarg_0);
writeStrIL.Emit(OpCodes.Ldfld, yField);
writeStrIL.Emit(OpCodes.Box, typeof(int));
// Now, you have all of the arguments for your call to
// Console.WriteLine(string, object, object) atop the stack:
// the string InStr, a reference to the boxed value of 'x', and
// a reference to the boxed value of 'y'.
// Call Console.WriteLine(string, object, object) with EmitCall.
writeStrIL.EmitCall(OpCodes.Call, writeLineMI, null);
// Lastly, EmitWriteLine can also output the value of a field
// using the overload EmitWriteLine(FieldInfo).
writeStrIL.EmitWriteLine("The value of 'x' is:");
writeStrIL.EmitWriteLine(xField);
writeStrIL.EmitWriteLine("The value of 'y' is:");
writeStrIL.EmitWriteLine(yField);
// Since we return no value (void), the the ret opcode will not
// return the top stack value.
writeStrIL.Emit(OpCodes.Ret);
return pointTypeBld.CreateType();
}
public static void Main() {
object[] ctorParams = new object[2];
Console.Write("Enter a integer value for X: ");
string myX = Console.ReadLine();
Console.Write("Enter a integer value for Y: ");
string myY = Console.ReadLine();
Console.WriteLine("---");
ctorParams[0] = Convert.ToInt32(myX);
ctorParams[1] = Convert.ToInt32(myY);
Type ptType = CreateDynamicType();
object ptInstance = Activator.CreateInstance(ptType, ctorParams);
ptType.InvokeMember("WritePoint",
BindingFlags.InvokeMethod,
null,
ptInstance,
new object[0]);
}
}

How to call public functions dynamically at run time

I want to call the functions by their name at run time like
string srFunctionName="MyFunction";
So with using this variable i want to call function named as "MyFunction". How can i do that ?
You could use Reflection:
string strFunctionName = "MyFunction";
// get the type containing the method
Type t = Type.GetType("Foo.Bar.SomeTypeContainingYourFunction");
// you will need an instance of the type if the method you are
// trying to invoke is not static. If it is static you could leave that null
object instance = Activator.CreateInstance(t);
// the arguments that your method expects
new object[] arguments = new object[] { 1, "foo", false };
// invoke the method
object result = t.InvokeMember(
strFunctionName,
BindingFlags.InvokeMethod,
null,
instance,
arguments
);
UPDATE:
As requested in the comments section here's a full example with real functions:
using System;
using System.Reflection;
namespace Foo.Bar
{
public class SomeTypeContainingYourFunction
{
public string MyFunction(int foo, string bar, bool baz)
{
return string.Format("foo: {0}, bar: {1}, baz: {2}", foo, bar, baz);
}
}
}
namespace Bazinga
{
class Program
{
static void Main()
{
var strFunctionName = "MyFunction";
var t = Type.GetType("Foo.Bar.SomeTypeContainingYourFunction");
var instance = Activator.CreateInstance(t);
var arguments = new object[] { 1, "foo", false };
var result = t.InvokeMember(
strFunctionName,
BindingFlags.InvokeMethod,
null,
instance,
arguments
);
Console.WriteLine(result);
}
}
}
Here is an example to close the a form
object instance = form;
Type myType = form.GetType();
myType.InvokeMember("Close", BindingFlags.InvokeMethod, null, instance, null);
You can use reflection to create an object of a class and then call a function using that object.
object Instance = Activator.CreateInstance(t); // t is type
MethodInfo mi = t.GetMethod(srFunctionName);
if (mi != null)
mi.Invoke(Instance, args);
else
logError();

Instantiate an object with a runtime-determined type

I'm in a situation where I'd like to instantiate an object of a type that will be determined at runtime. I also need to perform an explicit cast to that type.
Something like this:
static void castTest(myEnum val)
{
//Call a native function that returns a pointer to a structure
IntPtr = someNativeFunction(..params..);
//determine the type of the structure based on the enum value
Type structType = getTypeFromEnum(val);
structType myStruct = (structType)Marshal.PtrToStructure(IntPtr, structType);
}
This is obviously not valid code, but I hope it conveys the essence of what I'm trying to do. The method I'm actually working on will have to perform the marshaling operation on ~35 different types. I have several other methods that will need to do something similar with the same set of types. So, I'd like to isolate the type-determining logic from these methods so that I only need to write it once, and so that the methods stay clean and readable.
I must admit to being a total novice at design. Could anyone suggest a good approach to this problem? I suspect there might be an appropriate design pattern that I'm unaware of.
There are several ways you can create an object of a certain type on the fly, one is:
// determine type here
var type = typeof(MyClass);
// create an object of the type
var obj = (MyClass)Activator.CreateInstance(type);
And you'll get an instance of MyClass in obj.
Another way is to use reflection:
// get type information
var type = typeof(MyClass);
// get public constructors
var ctors = type.GetConstructors(BindingFlags.Public);
// invoke the first public constructor with no parameters.
var obj = ctors[0].Invoke(new object[] { });
And from one of ConstructorInfo returned, you can "Invoke()" it with arguments and get back an instance of the class as if you've used a "new" operator.
You can mostly do what you're describing, but since you don't know the type at compile-time, you'll have to keep the instance loosely-typed; check its type at each point you use it, and cast it appropriately then (this will not be necessary with c# 4.0, which supports dynamics):
Type type = CustomGetTypeMethod();
var obj = Activator.CreateInstance(type);
...
if(obj is MyCustomType)
{
((MyCustomType)obj).Property1;
}
else if (obj is MyOtherCustomType)
{
((MyOtherCustomType)obj).Property2;
}
I think you're looking for Activator.CreateInstance
Creating an instance of a run-time determined Type is easy, using Activator.CreateInstance, as others have mentioned. However, casting it, as you do in your example on the Marshal.PtrToStructure line is not possible, as the type has to be known at compile time for casting. Also, note that Activator.CreateInstance can not be used in conjunction with an IntPtr.
If your types have a common base class (other than Object), you can cast it to said base type and call functions on that. Otherwise, calling functions will only be possible using reflection.
So either:
static void castTest(myEnum val)
{
//Call a native function that returns a pointer to a structure
IntPtr val = someNativeFunction(..params..);
//determine the type of the structure based on the enum value
Type structType = getTypeFromEnum(val);
BaseClass myStruct = (BaseClass)Marshal.PtrToStructure(IntPtr, structType);
myStruct.SomeFunctionDeclaredInBaseClass();
}
Or:
static void castTest(myEnum val)
{
//Call a native function that returns a pointer to a structure
IntPtr val = someNativeFunction(..params..);
//determine the type of the structure based on the enum value
Type structType = getTypeFromEnum(val);
object myStruct = Marshal.PtrToStructure(IntPtr, structType);
MemberInfo[] function = FindMembers(MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance,
(MemberFilter)delegate(MemberInfo info, object filter)
{
return info.Name == filter.ToString();
}, "SomeFunction");
if (mi.Length > 0 && mi[0] is MethodInfo)
((MethodInfo)mi[0]).Invoke(myStruct, ..params..);
}
You could go dynamic:
using System;
namespace TypeCaster
{
class Program
{
internal static void Main(string[] args)
{
Parent p = new Parent() { name = "I am the parent", type = "TypeCaster.ChildA" };
dynamic a = Convert.ChangeType(new ChildA(p.name), Type.GetType(p.type));
Console.WriteLine(a.Name);
p.type = "TypeCaster.ChildB";
dynamic b = Convert.ChangeType(new ChildB(p.name), Type.GetType(p.type));
Console.WriteLine(b.Name);
}
}
internal class Parent
{
internal string type { get; set; }
internal string name { get; set; }
internal Parent() { }
}
internal class ChildA : Parent
{
internal ChildA(string name)
{
base.name = name + " in A";
}
public string Name
{
get { return base.name; }
}
}
internal class ChildB : Parent
{
internal ChildB(string name)
{
base.name = name + " in B";
}
public string Name
{
get { return base.name; }
}
}
}
methodName = NwSheet.Cells[rCnt1, cCnt1 - 2].Value2;
Type nameSpace=typeof(ReadExcel);
Type metdType = Type.GetType(nameSpace.Namespace + "." + methodName);
//ConstructorInfo magicConstructor = metdType.GetConstructor(Type.EmptyTypes);
//object magicClassObject = magicConstructor.Invoke(new object[] { });
object magicClassObject = Activator.CreateInstance(metdType);
MethodInfo mthInfo = metdType.GetMethod("fn_"+methodName);
StaticVariable.dtReadData.Clear();
for (iCnt = cCnt1 + 4; iCnt <= ShtRange.Columns.Count; iCnt++)
{
temp = NwSheet.Cells[1, iCnt].Value2;
StaticVariable.dtReadData.Add(temp.Trim(), Convert.ToString(NwSheet.Cells[rCnt1, iCnt].Value2));
}
//if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_AddNum" || Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_SubNum")
//{
// //StaticVariable.intParam1 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 4].Value2);
// //StaticVariable.intParam2 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 5].Value2);
// object[] mParam1 = new object[] { Convert.ToInt32(StaticVariable.dtReadData["InParam1"]), Convert.ToInt32(StaticVariable.dtReadData["InParam2"]) };
// object result = mthInfo.Invoke(this, mParam1);
// StaticVariable.intOutParam1 = Convert.ToInt32(result);
// NwSheet.Cells[rCnt1, cCnt1 + 2].Value2 = Convert.ToString(StaticVariable.intOutParam1) != "" ? Convert.ToString(StaticVariable.intOutParam1) : String.Empty;
//}
//else
//{
object[] mParam = new object[] { };
mthInfo.Invoke(magicClassObject, mParam);

Dynamically invoking any function by passing function name as string

How do I automate the process of getting an instance created and its function executed dynamically?
Thanks
Edit: Need an option to pass parameters too. Thanks
Do you just want to call a parameterless constructor to create the instance? Is the type specified as a string as well, or can you make it a generic method? For example:
// All error checking omitted. In particular, check the results
// of Type.GetType, and make sure you call it with a fully qualified
// type name, including the assembly if it's not in mscorlib or
// the current assembly. The method has to be a public instance
// method with no parameters. (Use BindingFlags with GetMethod
// to change this.)
public void Invoke(string typeName, string methodName)
{
Type type = Type.GetType(typeName);
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod(methodName);
method.Invoke(instance, null);
}
or
public void Invoke<T>(string methodName) where T : new()
{
T instance = new T();
MethodInfo method = typeof(T).GetMethod(methodName);
method.Invoke(instance, null);
}
To invoke a constructor, Activator.CreateInstance will do the trick. It has a bunch of overloads to make your life easier.
If your constructor is parameterless:
object instance = Activator.CreateInstance(type)
If you need parameters:
object instance = Activator.CreateInstance(type, param1, param2)
To invoke, a method, once you have the Type object you can call GetMethod to get the method, and then Invoke (with or without parameters) to invoke it. Should you need it, Invoke will also give you the return value of the function you're calling (or null if its a void method),
For a slightly more detailed sample (paste into a console app and go):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
namespace Test
{
public static class Invoker
{
public static object CreateAndInvoke(string typeName, object[] constructorArgs, string methodName, object[] methodArgs)
{
Type type = Type.GetType(typeName);
object instance = Activator.CreateInstance(type, constructorArgs);
MethodInfo method = type.GetMethod(methodName);
return method.Invoke(instance, methodArgs);
}
}
class Program
{
static void Main(string[] args)
{
// Default constructor, void method
Invoker.CreateAndInvoke("Test.Tester", null, "TestMethod", null);
// Constructor that takes a parameter
Invoker.CreateAndInvoke("Test.Tester", new[] { "constructorParam" }, "TestMethodUsingValueFromConstructorAndArgs", new object[] { "moo", false });
// Constructor that takes a parameter, invokes a method with a return value
string result = (string)Invoker.CreateAndInvoke("Test.Tester", new object[] { "constructorValue" }, "GetContstructorValue", null);
Console.WriteLine("Expect [constructorValue], got:" + result);
Console.ReadKey(true);
}
}
public class Tester
{
public string _testField;
public Tester()
{
}
public Tester(string arg)
{
_testField = arg;
}
public void TestMethod()
{
Console.WriteLine("Called TestMethod");
}
public void TestMethodWithArg(string arg)
{
Console.WriteLine("Called TestMethodWithArg: " + arg);
}
public void TestMethodUsingValueFromConstructorAndArgs(string arg, bool arg2)
{
Console.WriteLine("Called TestMethodUsingValueFromConstructorAndArg " + arg + " " + arg2 + " " + _testField);
}
public string GetContstructorValue()
{
return _testField;
}
}
}
Assuming that the method you want to invoke does not take any parameters:
public void InvokeMethod(Type type, string methodName)
{
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
method.Invoke(instance, null);
}
I think your problem is little too generic here, I am providing a solution with certain assumptions here.
Assumption: you have a typeName (string), methodName (string), and a parameter (of SomeType).
public static void InvokeMethod(string typeName, string methodName, SomeType objSomeType) {
Type type = Type.GetType(typeName);
if(type==null) {
return;
}
object instance = Activator.CreateInstance(type); //Type must have a parameter-less contructor, or no contructor.
MethodInfo methodInfo =type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public);
if(methodInfo==null) {
return;
}
methodInfo.Invoke(instance, new[] { objSomeType });
}
let me know know if my assumptions are wrong.
To pass the parameters dynamically
Here I have taken params string[] args, because different functions have different number of parameters so.
public void Invoke(string typeName,string functionName,params string[] args)
{
Type type = Type.GetType(typeName);
dynamic c=Activator.CreateInstance(type);
//args contains the parameters(only string type)
type.InvokeMember(functionName,BindingFlags.InvokeMethod,null,c,args);
}

Categories