Posts Tagged ‘C#’

More Impressions of C#: 3.0

September 12, 2009

The topic of this post is basically: lambdas are awesome.

C# 3.0 introduced lambda expressions with type inference and a set of generic delegates in the .NET framework.  That means you can do this:

event Action<string> MyEvent;

MyClass.MyEvent += (s) => { doStuff(s, 5) };

The => operator defines an anonymous method (lambda) taking the arguments on the left to the statements or expression on the right.  Types can be specified, but don’t have to be — the compiler can infer them, in this case from the event type.  Note that it takes exactly one simple short line to define an event, and one simple short line to connect it.  There is no redundancy or boilerplate code, and the function handling the event does not have to be written specifically for that purpose.  Sweet.

The above is roughly equivalent to, in PyQt:

self.emit(SIGNAL(“myEvent”),”foo”)

self.connect(someObj, SIGNAL(“myEvent”), lambda s: doStuff(s, 5))

In Qt with C++, you would have to define an extra method if you just wanted to pass an extra argument like this.  There are of course many other uses for lambdas.  One new use in C# 3.0/.NET 3.5 is the LINQ framework, which defines extension methods for common types, in particular IEnumerables that, in the simplest use, allow you to use lambda expressions to execute queries:

IEnumerable FilteredList = MyList.Where(person => person.Name == “bob”);

LINQ also allows you to write these queries using an SQL-like syntax.

The hundreds of other posts and documents online can explain it all better than I can, but finding things like this makes me like C# more and more.

Advertisements