none
C# passing function as argument RRS feed

  • Question

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

    when i am passing function name this way return RunTheMethod(Method1); then i want to also pass argument to for the Method1 function.

    in this sample hard code the argument for the method1 which i do not like rather i want to pass argument with this line return RunTheMethod(Method1);

    tell me how to achieve it. thanks

    Thursday, May 31, 2018 7:54 PM

Answers

  • The argument is just a string.  No magic required.

    public bool RunTheMethod(Func<string, int> myuMethodName, string myParam )
    {
        int i = myMethodName(myParam);
    }
    
    public bool Test()
    {
        return RunTheMethod( Method1, "parameter" );
    }



    Tim Roberts, Driver MVP Providenza & Boekelheide, Inc.

    • Proposed as answer by Dolen Zhang Friday, June 1, 2018 3:31 AM
    • Marked as answer by Sudip_inn Friday, June 1, 2018 2:09 PM
    Friday, June 1, 2018 12:55 AM