How to invoke without parameters method?

asp.net, c#

Solution

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");

Problem

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. ```

Original source

Related problems