Search code examples
c#lambdadelegates.net-3.5function-pointers

Pass a method as a parameter in C# from a different class


I have a class "A" from which I want to call a method in another different class "B" by passing a function as a parameter. Function passed as a parameter is in class B. So how to do it if I am calling method from class A?

I am using Visual Studio 2008 and .NET Framework 3.5.

I have seen this post but it tells how to call a main method by passing another method as a parameter but from the same class, not different class.

For example, in that post below example is provided:

public class Class1
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
}

but how to do the following:

public Class A
{
        (...)

        public bool Test()
        {
            return RunTheMethod(Method1);
        }

        (...)
}


public class B
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }
}

Solution

  • You would need to make an instance of class B inside class A and then call the method, For example, change your class A to:

    public Class A
    {
            (...)
            private B myClass = new B();
            public bool Test()
            {
                return myClass.RunTheMethod(myClass.Method1);
            }
    
            (...)
    }