I have one class in which public method without input parameter.
public partial class MyClass: System.Web.UI.MasterPage
{
public void HelloWorld() {
Console.WriteLine("Hello World ");
}
}
I want to invoke HelloWorld()
method into my another class
public partial class ProductType_Showpt : System.Web.UI.Page
{
protected void ChkChanged_Click(object sender, EventArgs e)
{
MyClass master =(MyClass) this.Master;
master.GetType().GetMethod("HelloWorld").Invoke(null, null);
}
}
but it's throw this exception
Object reference not set to an instance of an object.
I believe your Invoke
method shouldn't take null
parameter as a first one.
MyClass yourclass = new MyClass();
MyClass.GetType().GetMethod("HelloWorld").Invoke(yourclass , null);
For first parameters from MethodBase.Invoke
The object on which to invoke the method or constructor. If a method is static, this argument is ignored. If a constructor is static, this argument must be null or an instance of the class that defines the constructor.
Here you haven't use the class as first parameter in Invoke
ie, you have to apply code as below.
MyClass master= new MyClass();
master.GetType().GetMethod("HelloWorld").Invoke(objMyClass, null);
Now there may be another possibility of throwing error if you have another method with some parameters(Overloaded method). In such case, you have to write code specifying you need to invoke the method which doesn't have parameters.
MyClass master= new MyClass();
MethodInfo mInfo = master.GetType().GetMethods().FirstOrDefault
(method => method.Name == "HelloWorld"
&& method.GetParameters().Count() == 0);
mInfo.Invoke(objMyClass, null);
Now if you class instance is not known in advance you can use the following code. Use Fully Qualified Name inside Type.GetType
Type type = Type.GetType("YourNamespace.MyClass");
object objMyClass = Activator.CreateInstance(type);
MethodInfo mInfo = objMyClass.GetType().GetMethods().FirstOrDefault
(method => method.Name == "HelloWorld"
&& method.GetParameters().Count() == 0);
mInfo.Invoke(objMyClass, null);
If your class instance is unknown in advance, and is in another assembly, Type.GetType
may return null. In such case, for the above code, instead of Type.GetType
, call the below method
public Type GetTheType(string strFullyQualifiedName)
{
Type type = Type.GetType(strFullyQualifiedName);
if (type != null)
return type;
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
type = asm.GetType(strFullyQualifiedName);
if (type != null)
return type;
}
return null;
}
And call like
Type type = GetTheType("YourNamespace.MyClass");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With