0

The following code outputs bee:

    var str = "B";

    var env = new Func<string>(() => {
        switch (str)
        {
            case "A":
                return "aye";
            case "B":
                return "bee";
            default:
                return "see";
        }
    }).Invoke();

    Console.WriteLine(env);

How can I pass the str variable as a parameter to the anonymous function? The closest I can get is this:

    var str = "B";

    Func<string, string> env = a => {
        switch (a)
        {
            case "A":
                return "aye";
            case "B":
                return "bee";
            default:
                return "see";
        }
    };

    Console.WriteLine(env(str));

But that is not anonymous, as it is named env.

Is it possible to use the first form and still pass in a parameter?

10
  • 3
    "But that is not anonymous, as it is named env." - that is still an anonymous method; env is the name of a local variable that holds a delegate instance that points to the anonymous method. Can you perhaps be more specific as to what you're trying to achieve, and what you mean by "anonymous" here (as it doesn't seem to be quite the usual meaning)? Dec 6, 2018 at 11:28
  • 1
    var env = new Func<string, string>((a) => { ...}.Invoke(str)? Dec 6, 2018 at 11:28
  • Thank you @dmitry-bychenko - that should have been obvious! Please post that as an answer and I'll accept.
    – Matt W
    Dec 6, 2018 at 11:46
  • @DmitryBychenko I think you are missing one ) before .Invoke plus (a) can be just a :)
    – Wanton
    Dec 6, 2018 at 11:46
  • 1
    that's also a delegate (reference) that points to an anonymous method instance - just... without a closure. (edit: see my later comment - I snafud the language here; the first version has a closure, the second version does not) Dec 6, 2018 at 11:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.