views:

106

answers:

2

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)

+6  A: 

Look into anonymous methods... for example this: http://stackoverflow.com/questions/1748719/c-anonymous-delegate

Daniel Mošmondor
Thanks; just knowing the term "anonymous delegate" let me find plenty of examples very quickly.
divider
"I don't know what I don't know" ~ I `hate` when I run into that one. Glad you found what you needed @divider
drachenstern
+5  A: 

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

Tor
I ended up with "new OperatorDefinition("*",2,4,true, delegate(double[] args){return args[0]*args[1];}"; is this any worse than yours?
divider
It's a matter of taste - I think Lambda is shorter and more readable
Tor
Thanks for the help, but the link to MSDN got truncated.
divider