locked
High-order Function question... RRS feed

  • Question

  • Hello, I'm newbie to c#, and I was reading on my book that I can pass functions as parameters and receive functions or both... so I'm trying to make an exercise but can't make this work... please help!

    My idea is to create a static function like this:
    C#:
    public static void TestMethod<T1, TResult>(Func<T1, TResult> myfunction ) {
                ...
    }
    Now, the idea is that I can call this static method by providing a function that matches the T1 and the TResult like this:
    C#:
    Func<string, string> ChangeName = name => $"My name is: {name}";
    
    TestMethod<string, string>(ChangeName);
    Now my understanding is that inside the TestMethod I received a function, now I can make use of the myfunction and call it to action, am I right? in this case, if I call the function it should return an string (according to my definition), so I think I should be able to do this:
    C#:
    public static void TestMethod<T1, TResult>(Func<T1, TResult> myfunction ) {
        Console.WriteLine(    myfunction.Invoke()        );
            // or
        Console.WriteLine(    myfunction()    );
    }
    But I can't because it display an error asking for a T1 parameter...
    Untitled.png


    PLEASE HELP!...
    Monday, April 13, 2020 3:34 AM

All replies

  • The T1 is the input parameter which we need to take as method parameter which you are missing in your method definition:

    public static void TestMethod<T1, TResult>(Func<T1, TResult> myfunction, T1 parameter ) 
    {
        return myfunction(parameter);
    }


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, April 13, 2020 4:38 AM
  • Hi,

    Has your issue been resolved?

    If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, April 22, 2020 8:56 AM