Search code examples
c#.netwinformsmethodsprivate-methods

Call a Non-Static Method in Another Project and Namespace


I have two Windows forms applications that belong to separate solutions. I'm trying to call a method from one using the other. I created a class library from the solution I'm trying to access (Sol1) and referenced it in the project I'm running (Sol2) but I'm having difficulty accessing the method.

I found this solution that suggests doing it this way:

string s = string InvokeStringMethod3 ("TheProject", "TheNamespace", "TheClass", "TheMethod");

public static string InvokeStringMethod3(
                        string assemblyName,
                        string namespaceName,
                        string typeName,
                        string methodName)
{
    Type calledType = Type.GetType(namespaceName + "." + typeName + "," + assemblyName);
    String s = (String)calledType.InvokeMember(
                    methodName,
                    BindingFlags.InvokeMethod | BindingFlags.Public | 
                        BindingFlags.Static,
                    null,
                    null,
                    null);
}

When I run it, I get a NullReferenceException where calledType is null. According to the comments, this will only work on static methods but the method I'd trying to call is public void.

Is there a way to modify this to work for a non-static method? Or should this be done another way? I'm working with C# in Visual Studio 2015, and both projects are .NET.


Solution

  • Create an object of the class and use its function when you have already referenced the solution. No need to to create a method static. Inside solution 2 instantiate your solution 1class.

    Sol1.MyClass cls = new Sol1.MyClass();
    

    Then you can use the method.

    cls.somemethod();
    

    Static members belong to the class not to the object and Can be used directly by class name.