Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding delegate in C# [duplicate]

Tags:

c#

delegates

f#

How does one add a new function to a delegate without using the += notation ?

I wonder how to do his from another CLR langage, namely F#. (I know there are much nicer way to deal with events in F#, but I am being 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 pointed out by Daniel in the comments, the fact that one has no direct way of doing this probably is a design decision by dotnet team to not mutate the queue too much.

like image 614
nicolas Avatar asked Mar 29 '13 13:03

nicolas


1 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)
like image 198
pad Avatar answered Oct 03 '22 00:10

pad