Dunno
Dunno

Reputation: 3684

How to return a c# function like in python?

I'm trying to do something that could be done like so in python:

class Spam():
    def print_four_numbers(a, b, c, d):
        print a, b, c, d

class Beacon():
    def bar(SpamInstance):
        return SpamInstance.print_four_numbers

B, S = Beacon(), Spam()

The key thing here is that the above code allows me to do this:

>>>B.bar(S)(1, 2, 3, 4)
1 2 3 4

How can I do something similar with C#? If it changes anything, I need the "print_four_numbers" method to be overloaded 3-4 times. I've read about delegates and events but will they work here (and how)?

Also I know that this could be solved by simply passing all those arguments to bar() and "passing them on" to another function, but I dislike having methods with a lot of arguments.

Thanks!

Upvotes: 0

Views: 76

Answers (1)

Max Yankov
Max Yankov

Reputation: 13327

class Spam
{
    public void PrintFourNumbers(int a, int b, int c, int d)
    {
        Console.WriteLine(string.Join(" ", new[] {a, b, c, d}));
    }
}

class Beacon
{
    public System.Action<int, int, int, int> Bar(Spam instance)
    {
        return instance.PrintFourNumbers;
    }
}

class Program
{
    public static void Main()
    {
        var b = new Beacon();
        var s = new Spam();
        b.Bar(s)(1, 2, 3, 4);
    }
}

The PrintFourNumbers method is pretty ugly; it would look much nicer if it accepted an array of integers, but I wanted to keep it as close to example in the question as possible.

Upvotes: 1

Related Questions