Wednesday 21 July 2010

Lambda, delegate, anonymous & implicit goodness in C#

Spent last night reading up on some of the finer points of C# in Jon Skeet’s excellent book C# in depth (http://manning.com/skeet/)

I have introduced some of the newly learned syntaxes into my DSL parser. I have included a step by step explanation of some of these syntaxes that may appear alien to a .NET 2.0 developer.

I created an inline delegate function to be used within my tokeniser function to determine if a string character was a double or single quote as follows:-

Func<string,bool> IsQuote = a=>(new [] {"\"","'"}).Contains(a);

...and called within the same function...

if (IsQuote(c)){//do something}

Breaking this down into it’s constituent parts we have

Part 1

Func<string,bool> IsQuote = a=>(new [] {"\"","'"}).Contains(a);

Declare (a pointer to) a function that accepts a string parameter and returns a bool. This uses the Func<T,U> type, the last generic always representing the return type.

Part 2

Func<string,bool> IsQuote = a=>(new [] {"\"","'"}).Contains(a);

Assign the function definition to this function pointer.

“a” is an implicit (string) type as it represents the first parameter in the function so the string declaration can be dropped

“a=>” is shorthand for delegate (string a){...}

A more verbose version might look like this…

Func<string, bool> IsQuoteAlso;

IsQuoteAlso = delegate(string a) { return a == "\"" || a == "'"; };

 Part 3

Func<string,bool> IsQuote = a=>(new [] {"\"","'"}).Contains(a);

Create a new array of strings using an implicit declaration (the compiler figures out that this is a new array of strings) and then call the contains method.

The next question is, will these syntaxes become part of everyday development; will a “regular” developer be able to work with these new shortcuts. Time will tell.

Jon.

No comments: