Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-made delegates for operators?

Tags:

c#

Supposing I want to use the addition operator (+) as a delegate, how would I pass that to a method?

Looking for something similar to Python's operator.add.

e.g., instead of

var center = _drawingPoly.Aggregate((a, b) => a + b)/_drawingPoly.Count;

I'd want to write something like:

var center = _drawingPoly.Aggregate(operator+)/_drawingPoly.Count;

(FYI, + is overloaded here)

like image 587
mpen Avatar asked Dec 03 '25 18:12

mpen


1 Answers

There's nothing built-in, but you could do it using expression trees:

public static Func<T, T, T> OpAdd<T>()
{
    var param1Expr = Expression.Parameter(typeof(T));
    var param2Expr = Expression.Parameter(typeof(T));
    var addExpr = Expression.Add(param1Expr, param2Expr);
    var expr = Expression.Lambda<Func<T, T, T>>(addExpr, param1Expr, param2Expr);

    return expr.Compile();
}

which you can then use like:

var center = _drawingPoly.Aggregate(OpAdd<int>())/_drawingPoly.Count;

unfortunately this approach isn't type-safe, and you'll probably want to cache the resulting delegates that are created.

like image 59
Lee Avatar answered Dec 06 '25 07:12

Lee



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!