Adding a delegate in C #

How to add a new function to a delegate without using the + = symbol

I wonder how to make it from another CLR language, namely F #. (I know there is a much better way to handle events in F #, but I'm curious ..)

static int Square (int x) { return x * x; }
static int Cube(int x) { return x * x * x; }
delegate int Transformer (int x);

Transformer d = Square ;
d += Cube;

Edit

As Daniel noted in the comments, the fact that he has no direct way to do this is probably a constructive solution to the dotnet command not to mutate the queue too much.

+5
source share
2 answers

Here is one way to do it in F #. You need downcasting due to the use of Delegate.Combine :

let square x = x * x
let cube x = x * x * x

type Transformer = delegate of int -> int

let inline (++) (a: 'T) (b: 'T) = 
    System.Delegate.Combine(a, b) :?> 'T

let d = Transformer(square)
let e = d ++ Transformer(cube)
+6
source

Delegate.Combine?

d = (Transformer) Delegate.Combine(d, new Transformer(Cube));
+2
source

All Articles