Josef Kvita Josef Kvita - 1 month ago 11
C# Question

C# - Passing functions (with arguments) as arguments of a function

I need to create a function, that will take another functions (always different quantity of them). Can someone help me please?

Function DoThisFunction will have different types and quantity of parameters.
there can be different number of condition functions.

I'll try to show it here:

bool MyFunction(condition1(args), condition2(args), condition3(args), ... , DoThisFunction(args))
{
...
if (condition1(int x) == true && condition2(int x, string C) == 5)
{
DoThisFunction(par1, par2, par3 ...);
return true;
}
}

bool condition1(int x)
{
if (x>5)
return true;
else
return false;
}

int condition2(int x, string C)
{
....
return par1;
}


etc...

Then I need to call:

bool z = MyFunction(condition1(int x)==true, condition2(int x, string C)==5, DoThisFunction(par1, anotherArguments ...))

Answer

I would like to suggest another approach for your code. Maybe, you can keep a separated list with all the functions you need to verify, and run each method inside a very simple loop (foreach), in this case:

  • the code will be very friendly (easy to understand)
  • better maintainability
  • you can review less code and add more functionality (for instance, you may inject some code and just add another Func<> into your List<>)

Please, take a look at the following example:

static class Program
{
    private static void Main(string[] args)
    {
        var assertions = new List<Func<object[], bool>>
        {
            Assertion1,
            Assertion2,
            Assertion3
        };

        var yourResult = Assert(assertions, 1, "1", true);
        Console.WriteLine(yourResult); // returns "True" in this case
        Console.ReadLine();
    }

    private static bool Assert(IEnumerable<Func<object[], bool>> assertions, params object[] args)
    {
        // the same as
        // return assertions.Aggregate(true, (current, assertion) => current & assertion(args));

        var result = true;

        foreach (var assertion in assertions)
            result = result & assertion(args);

        return result;
    }

    private static bool Assertion1(params object[] args)
    {
        return Convert.ToInt32(args[0]) == 1;
    }

    private static bool Assertion2(params object[] args)
    {
        return Convert.ToInt32(args[0]) == Convert.ToInt32(args[1]);
    }

    private static bool Assertion3(params object[] args)
    {
        return Convert.ToBoolean(args[2]);
    }
}