Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an expression as a parameter to a method

Tags:

c#

I am trying to pass an expression as parameter to a function like:

public string MyFunction(bool expression) //what should I set here as parameter type?
{
    return expression ? "True" : "False";
}

public void InvokeMyFunction()
{
    var myString = MyFunction(10 > 1);
}
like image 842
Naughty Ninja Avatar asked Feb 27 '26 23:02

Naughty Ninja


1 Answers

You can pass Func<bool> to represent a method that returns a boolean. Also when you declare the function, you can use lambda syntax () => to represent an anonymous method.

string MyFunction(Func<bool> expression)
{
    return expression() ? "True" : "False";
}

void InvokeMyFunction()
{
    var myString = MyFunction(() => 10 > 1);
}
like image 128
TVOHM Avatar answered Mar 02 '26 14:03

TVOHM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!