Reputation: 270
How can I pass a bitwise operator as a parameter to my method? I've read some articles that describes how to pass for example equality operator as a parameter however they implement it in some way and after this pass it with a delegate. In my case I'm not sure how to implement the bitwise operator.
Upvotes: 1
Views: 1591
Reputation: 843
You can use Func<>
int MyFunc(int input1, int input2, Func<int, int, int> bitOp)
{
return bitOp(input1, input2);
}
Use like this
Console.WriteLine(MyFunc(1, 2, (a, b) => a | b));
Outputs "3"
Upvotes: 5
Reputation: 2742
Appreciate the answer has already been accepted at this point, but thought I would at least share another possible approach:
int result = Bitwise.Operation(1, 2, Bitwise.Operator.OR); // 3
Declared as:
public static class Bitwise
{
public static int Operation(int a, int b, Func<int, int, int> bitwiseOperator)
{
return bitwiseOperator(a, b);
}
public static class Operator
{
public static int AND(int a, int b)
{
return a & b;
}
public static int OR(int a, int b)
{
return a | b;
}
}
}
Upvotes: 5