C#: Our own lambda expression with arguments as parameter? Why not?

Many methods in the .NET base class libraries define methods that require delegate types as parameters. Why we love delegates? Because they are a better anonymous methods which provide us new easy and quick to use syntax:

var list = new List<int>() {1, 12, 4, 45, 10, 17, 81, 19};
var number = list.FindAll(i => (i % 2) == 0);

Here we is an example how define our own class that could takes as argument lambda expression with arguments:

public class MyLambdaExpression
{
public delegate void MyDelegate(string msg, int result);
private MyDelegate mMyDelegate;

public void SetHandler(MyDelegate target)
{ mMyDelegate = target; }

public void Add(int x, int y)
{
if (mMyDelegate != null)
mMyDelegate.Invoke(“Complited compution!”, x + y);
}
}

And now let’s use Lambda Expression (it can be called e.g. in Main method for console app):

MyLambdaExpression myLambda = new MyLambdaExpression();
myLambda.SetHandler((message, result) => { Console.WriteLine(“Message: {0}, Result: {1}”, message, result); } );
myLambda.Add(2, 3);

Output:

Message: Complited compution!, Result: 5

So that’s all. Reassuming we write class with containing delegate object and method to initialize this object. Last method Add() call Invoke() method to handing all method assigned to delegate object. Simple?

Of course delegate can take no parameters:

public delegate void DelegateWithoutParams();

Handle the result of the invocation as follows:

DelegateWithoutParams d = new DelegateWithoutParams( () => { return “Returned value!”; } );
Console.WriteLine( d.Invoke() );

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s