Delegates, Anonymous Methods, Lambda Expressions, LINQ, and Testing

Let’s assume that the more a tester knows about coding, the better he will be able to test code. There is an interesting set of relationships between C# delegates, anonymous methods, lambda expressions, and LINQ. Each of these topics is relatively simple by itself but all of them are a bit tricky when considered together. First, in the vast majority of coding situations you write a method of some sort and then call it directly. For example, if a method SayHelloTo() is defined as:
static void SayHelloTo(string s) {
  Console.WriteLine("Hi there " + s);
then you can directly call the method like:
// call a method normally
which would output "Hi there George" to the screen. Of course you don’t need to code up a SayHelloTo() method — you could have just placed the code directly inline — so methods are just a way to make program code more readable, editable, and efficient. In .NET 1.x you can call a method indirectly using a delegate. For example:
delegate void StringInVoidOutDelegate(string s); // declare a delegate
static void Main(string[] args)
  // delegate calls via explicit method, .NET 1.x
  StringInVoidOutDelegate d1 = new StringInVoidOutDelegate(SayHelloTo);
Here the delegate named StringInVoidOutDelegate can act as an alias for any method which returns void and accepts a single string parameter. So if you had a second method, void SayGoodbyeTo(string t) { . . . }, you could call it using the same delegate like:
StringInVoidOutDelegate d2 = new StringInVoidOutDelegate(SayGoodByeTo);
OK, but what’s the point? It turns out that calling methods indirectly using delegates is very useful for certain programming scenarios including event-driven situations like those found in Windows application programming. Now in .NET 2.0 a new syntax called anonymous methods was introduced. Anonymous methods allow you to simplify your code a tiny bit, for example:
// delegate call via anonymous method, .NET 2.0
StringInVoidOutDelegate d3 =
  delegate(string s) { Console.WriteLine("Howdy " + s); };
Here instead of associating your delegate with some method defined elsewhere, you directly place the code into a delegate declaration. The only real advantage of anonymous methods is that they reduce the size of your source code somewhat. Now in .NET 3.0 a new syntax called lambda expressions was introduced. Lambda expressions allow you to simplify your code a tiny bit further, for example:
// delegate call via lambda expression, .NET 3.x
StringInVoidOutDelegate d4 =
  s => { Console.WriteLine("Aloha " + s); };
The => operator identifies a lambda expression. The operator is read, "goes to." Notice that you don’t declare the data type for the input parameter s. The data type will be inferred by the compiler. OK, but what’s the point of all this? Lambda expressions are never necessary, they’re just syntactic sugar coating. But lambda expressions make a nice companion to LINQ (Language Integrated Query) statements. LINQ is a set of ways to call into various data stores such as string arrays, XML, and SQL, in a unified way. For example:
string[] animals = { "ant", "bat", "cow", "dog", "elk" };
IEnumerable<string> query = animals
  .Where(a => a.Contains(‘o’))
  .Select(a => a.ToUpper());
foreach (string s in query) {
Whoa. Here you have a string collection and then use lambda syntax to extract just those strings which contain lower case ‘o’ and then convert those strings to all upper case. The output would be COW DOG. Notice that the "simple" lambda syntax has become a bit ugly, so there is yet another optional simplified form for lambda syntax which, confusingly, deletes the lambda operator, for example:
IEnumerable<string> query = from a in animals
  where a.Contains(‘o’)
  select a.ToUpper();
To summarize, delegates are a way to call methods indirectly. Anonymous methods are a way to simply calling delegates. Lambda expressions are a way to further simplify calling delegates. Lambda expressions are most useful with LINQ queries, and have a shortcut syntax which eliminates the identifying ‘=>’ operator.
This entry was posted in Software Test Automation. Bookmark the permalink.

One Response to Delegates, Anonymous Methods, Lambda Expressions, LINQ, and Testing

  1. Prashant says:

    Very well explained. This is what needed for people with advance skills to quickly fly over these kinds of article, instead of reading many pages long articles and books.
    Keep up the good work!

Comments are closed.