Dan Hall Dan Hall - 1 month ago 21
C# Question

instantiate object with reflection using constructor

I'm creating an instance of a class object using reflection and calling a method within that class:

// Get ExportLines type
Type type = typeof(ExportLines);

// Create an instance of ExportLines type
object obj = Activator.CreateInstance(type);

// Retrieve the variable method name from ExportLines
MethodInfo methodInfo = type.GetMethod("ExportLine_" + ExportLineNumber.ToString());

// Invoke the method on the instance created above with _Data object parameter
var val = methodInfo.Invoke(obj, new object[] { _Data, dataStrings});

//Add to txt file (later)
return val.ToString();


As you can see at the moment I'm invoking the method with a couple of parameters, what i actually want to do is initialise the class and with those parameters and set a global variable for use in all methods during that class instance.

Is this possible?

Thanks.

Answer

So you should add a constructor to the ExportLines class accepting _Data and dataStrings as parameters. This constructor should make sure it saves the passed parameters for later use, inside the ExportLine_n method. Now you can use the Activator.CreateInstance Method (Type, Object\[]) overload which creates an instance of the specified type using the constructor that best matches the specified parameters.