Friday, January 2, 2015

Using Anonymous Functions in C#

Recently started using a lot more anonymous functions in C#... probably due to JavaScript and Java's influence.

The first caveat with anonymous functions though is that they cannot be debugged. The whole block is basically a single command, you cannot step in while debugging.

I think that is also true in the other languages as well and related to how it's compiled.

So generally I would recommend you keep the functions in them small and simple, such as simple sorting or transformation logic.

You can replace any delegate parameter (including Predicate, Action, or Func, basically anything that wants a reference to a function) which an anonymous function.

For the 3 "special" types:

  • An Action again takes in 0 or more parameters and does something, returning no value.
  • A Func takes 0 or more parameters and returns 1 values.
  • A Predicate is a Func that usually returns -1, 0, 1 which defines the order between two input parameters.

http://stackoverflow.com/questions/4317479/func-vs-action-vs-predicate

If the anonymous function takes 0 parameters, you can pass it:

() => DoAction(someParameterInTheCallingFunction);

Sorry... can't remember a specific example... but it usually involves creating function calls which will be executed by another object that doesn't expect to pass it's own parameter values.

Or a you could define a block of code. I don't recommend this unless the block is small and pretty simple; the likelihood of debugging very close to 0.

() =>
{


}


If not, you can create a separate function matching the delegate signature and pass the function name as  the parameter itself:

MethodThatAcceptsFunc(DoSomething)

If you do that, you can debug the elements in the method body.

If the delegate accepts one or more multiple parameters like Func<object, int, int, int>

Use (int1, int2, int3) => return DoSomething(int1,int2,int3));

The signature for DoSomething would be object DoSomething(int a, int b, int c) and again you could just pass in the method directly.


No comments:

Post a Comment