Reputation: 449
I want to invoke a method from a string, but it doesn't let me pass null
as a parameter. The method does not require parameters.
private void reconnect_Click(object sender, EventArgs e)
{
string methodName = "data_load1";
//Get the method information using the method info class
MethodInfo mi = this.GetType().GetMethod(methodName);
//Invoke the method
mi.Invoke(this, null);
}
The data_load method:
private void data_load1()
{
this.dataTableAdapter.Fill(this.myDataSet.data);
}
I receive a NullReferenceException was unhandled
for mi.Invoke(this, null);
. Why is this not letting me pass a null
parameter?
Upvotes: 1
Views: 3517
Reputation: 19407
The problem is not the parameter - MethodInfo.Invoke()
allows null value for parameter.
Type: System.Object[]
An argument list for the invoked method or constructor. This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. If there are no parameters, parameters should be null. If the method or constructor represented by this instance takes a ref parameter (ByRef in Visual Basic), no special attribute is required for that parameter in order to invoke the method or constructor using this function. Any object in this array that is not explicitly initialized with a value will contain the default value for that object type. For reference-type elements, this value is null. For value-type elements, this value is 0, 0.0, or false, depending on the specific element type.
Above is from MSDN.
I expect the method is not found for whatever reason (typo?), and the MethodInfo
object is null.
On a side note, is there a reason why you are using reflection to call a private method from within the object instance - Why not invoke the method directly?
Upvotes: 0
Reputation: 887215
mi
is null.
To get a private method, you need to pass BindingFlags.Instance | BindingFlags.NonPublic
.
Upvotes: 6