Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#; making a new delegate without declaring the method separately?

I'm able to compile code that includes this:

OperationDelegate myOpDelegate;
static OperatorDefinition[] definitions ={
                new OperatorDefinition("+",2,3,true, new OperationDelegate(OperationAdd)),
            };
delegate double OperationDelegate(double[] args);
static double OperationAdd(double[] args)
            {
                return args[0] + args[1];
            }

but I think my code would look cleaner if I could do something more like this:

OperationDelegate myOpDelegate;
static OperatorDefinition[] definitions ={new OperatorDefinition("+",2,3,true, new OperationDelegate({return args[0]+args[1]}))};
delegate double OperationDelegate(double[] args);

because I want to define everything about each OperatorDefinition in a single place, rather than defining the functions separately. Is there some way to do this in C#?

(any other criticism about my code would be welcome, too)

like image 332
divider Avatar asked Oct 19 '10 19:10

divider


2 Answers

Look into anonymous methods... for example this: C# - Anonymous delegate

like image 65
Daniel Mošmondor Avatar answered Sep 24 '22 08:09

Daniel Mošmondor


You can use Lambda expressions as from .Net 3.5:

 static OperatorDefinition[] definitions ={
    new OperatorDefinition("+",2,3,true, 
        args => args[0] + args[1])
    };

In your OperatorDefinition constructor, last parameter should be of type Func<double[],double>

See: http://msdn.microsoft.com/en-us/library/bb397687.aspx

like image 24
Tor Avatar answered Sep 21 '22 08:09

Tor