How to call a method without parameters?

I have one class in which there is a public method without an input parameter.

 public partial class MyClass: System.Web.UI.MasterPage
   {

      public void HelloWorld() { 
       Console.WriteLine("Hello World "); 
      } 
    }

I want to call a method HelloWorld()in my other 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 this exception excludes

Object reference not set to an instance of an object.
+5
source share
4 answers

I believe that your method Invokeshould not accept the parameter nullas the first.

MyClass yourclass = new MyClass();    
MyClass.GetType().GetMethod("HelloWorld").Invoke(yourclass , null);

For the first parameters from MethodBase.Invoke

The object to call the method or constructor for. If the method is static, this argument is ignored. If the constructor is static, this argument must be null or an instance of the class that defines the constructor.

+5
source

You must specify an instance to execute the method:

MyClass myClassInstance = new MyClass();
MyClass.GetType().GetMethod("HelloWorld").Invoke(myClassInstance, null);
+1
source

Invoke, , .

MyClass master= new MyClass();  
master.GetType().GetMethod("HelloWorld").Invoke(objMyClass, null);

, (Overloaded method). , , , .

MyClass master= new MyClass();  
MethodInfo mInfo = master.GetType().GetMethods().FirstOrDefault
                (method => method.Name == "HelloWorld"
                && method.GetParameters().Count() == 0);
mInfo.Invoke(objMyClass, null);

, , . 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);

, Type.GetType null. Type.GetType

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;
}

Type type = GetTheType("YourNamespace.MyClass");
+1

You are trying to call a method on null instead of an instance of an object, you can call an instance method on an instance of the class, but not null. enter an instance of your class in the first parameter of the method HelloWorld.

MyClass myClassObject = new MyClass();    
MyClass.GetType().GetMethod("HelloWorld").Invoke(myClassObject, null);
0
source

All Articles