C# 3.0 - Lambda Expressions

"A lambda is an inline expression or statement block with a concise syntax that can be used in C# 3.0 and later wherever a delegate type is expected" . In a certain way we can consider Lambda Expressions as an evolution of the anonymous methods.

Look the examples below, at first sight the syntax looks very weird but when you know how they are built and you get used, you will see that it's extremely easy.

x => x + 1

x => { return x + 1; }

(x, y) => x == y

(int x, int y) => x * y

() => ExecuteAnyMethod();

Maybe you already noticed that a lambda consist of a list of input parameters, the operator "=>" (goes to) and a expression or statement. In the form of:

(input parameters) => Expression or Statement.

The list of parameters is optional, and you don't need to specify the types of the parameters in the cases where the type can be inferred. Parenthesis are also optional when we only specify one parameter.

After this fast overview the best is to see some code to understand better where Lambdas can be used.

   1: static void Main(string[] args)
   2: {
   3:     int[] numbers = { 1, 2, 3, 4, 5 };
   4:  
   5:     Filter filter = new Filter(IsEven);
   6:     // Filter filter = new Filter(IsOdd);
   7:  
   8:     PrintNumbers(numbers, filter);
   9:  
  10:     System.Console.ReadKey();
  11: }
  12:  
  13: static void PrintNumbers(int[] numbers, Filter filter)
  14: {
  15:     foreach (int number in numbers)
  16:     {
  17:         if (filter(number))
  18:             System.Console.WriteLine(number.ToString());
  19:     }
  20: }
  21:  
  22: static bool IsEven(int number)
  23: {
  24:     return number % 2 == 0;
  25: }
  26:  
  27: static bool IsOdd(int number)
  28: {
  29:     return !IsEven(number);
  30: }

The code is really simple, we want to print on the screen some numbers based on a filter condition. The filter condition "IsEven" is set through a delegate of type "Filter", that receives an int and returns true if ithe number satisfies the condition. With this kind of construction, we can easily switch which numbers must be printed without modifying the main business logic of PrintNumbers. As you can see in the code it would be as easy as replace line 7 by the line 6.

In C# 2.0 the code can be adjusted using anonymous method, so the filter condition is passed inline to PrintNumbers.

   1: public delegate bool Filter(int number);
   2:  
   3: static void Main(string[] args)
   4: {
   5:     int[] numbers = { 1, 2, 3, 4, 5 };
   6:  
   7:     PrintNumbers(numbers, delegate(int number) { return number % 2 == 0; });
   8:  
   9:     System.Console.ReadKey();
  10: }
  11:  
  12: static void PrintNumbers(int[] numbers, Filter filter)
  13: {
  14:     foreach (int number in numbers)
  15:     {
  16:         if (filter(number))
  17:             System.Console.WriteLine(number.ToString());
  18:     }
  19: }

With the anonymous method we don't need to declare the method IsEven and IsOdd anymore, we can just pass to PrintNumbers the condition to apply inline, look line 8.

Lambda expression improve anonymous methods providing a more concise syntax. Look how we can do the same with C# 3.0.

   1: static void Main(string[] args)
   2: {
   3:     int[] numbers = { 1, 2, 3, 4, 5 };
   4:  
   5:     PrintNumbers(numbers, number => number % 2 == 0);
   6:  
   7:     System.Console.ReadKey();
   8: }
   9:  
  10: static void PrintNumbers(int[] numbers, Funcint, bool> filter)
  11: {
  12:     foreach (int number in numbers)
  13:     {
  14:         if (filter(number))
  15:             System.Console.WriteLine(number.ToString());
  16:     }
  17: }

Look the line 5, we are still doing the same, but we don't need anymore the weird syntax of anonymous methods and the type int of parameter "number" is directly inferred. In addition note that we don't declare our custom Filter delegate anymore, but we use a delegate called Func. C# 3.0 introduces several default delegates that allow you to encapsulate methods which have from 0 to 4 parameters and return a value. They parameters and results types are generic, so with these delegates we cover a big percentage of the methods we normally use in our code.

Is this cool or what?

C# 3.0 - Object and Collection Initializers

With C# 3.0 you can initialize objects specifying the values of their visible properties and/or fields enclosed between brackets. The syntax is as easy as open the brackets and provide a list of name/value pairs separated by commas with all the properties/fields you want to initialize, the value of the field can be an expression or another initializer. Consider that using an object initializer without using the parenthesis of the constructor, is equivalent to invoking the default constructor. Next you a sample of how to initialize the same class with different styles.

   1: // Old Style
   2: Cookie cookie = new Cookie();
   3: cookie.Name = "MyCookie"
   4: cookie.Value = "Jose"
   5: cookie.Comment = "a cookie" 
   6:  
   7: // With Object initializer
   8: var cookie2 = new Cookie() { Name = "MyCookie", Value = "Jose", Comment = "a cookie" }; 
   9:  
  10: // Combining non default constructor and Object Initializer
  11: var cookie3 = new Cookie("MyCookie", "Jose") { Comment = "a cookie" }; 

Collection initializers allow us adding elements to a collection in a similar way we do in array initializers. The initializer consists of the list of elements we want to add separated by commas and enclosed by brackets. The elements can be single values or other initiliazers, but unlike object initializers they don't allow expressions to avoid confuse them. Below you can see some samples:

   1: // Collection Initializer
   2: var list = new ArrayList { "a", 1, "b"}; 
   3:  
   4: // Initialize collection that has Add method with more than one parameter
   5: var hash = new Hashtable { { 1, "one" }, { 2, "second" }, { 3, "third" } }; 
   6:  
   7: // Collection Initializer combined with Object Initializer
   8: var cookies = new List<Cookie> { new Cookie("cookie1", "1"), new Cookie("cookie2", "2") }; 

If you build your own collection, there are some requirements that the class must satisfy in order users can take profit of Collection Initializers. The class must implement the IEnumerable interface and must have at least one public "Add" method. Look the next code:

   1: static void Main(string[] args)
   2: {
   3:     Numbers numbers = new Numbers { 1, 2, 3, 4 }; 
   4:  
   5:     foreach (var n in numbers)
   6:     {
   7:         System.Console.WriteLine(n);
   8:     }
   9:     
  10:     System.Console.ReadKey();
  11: }
  12:  
  13: public class Numbers : System.Collections.IEnumerable
  14: {
  15:     List<int> numbers = new List<int>();
  16:  
  17:     public System.Collections.IEnumerator GetEnumerator()
  18:     {
  19:         foreach (int i in numbers)
  20:         {
  21:             yield return i;
  22:         }
  23:     }
  24:  
  25:     public void Add(int number)
  26:     {
  27:         numbers.Add(number);
  28:     }
  29: }

If you change the modifier of the method "Add" to private, the compiler will give the error "Numbers.Add(int) is inaccessible due to its protection level". This gives the hint that the compiler translates the Collection Initializer syntax to as much calls to the matching method Add as elements you add. We can verify it just examining the IL code.

IL_0000: newobj instance void Demo.Numbers::.ctor()
IL_0005: stloc.2
IL_0006: ldloc.2
IL_0007: ldc.i4.1
IL_0008: callvirt instance void Demo.Numbers::Add(int32)
IL_000d: ldloc.2
IL_000e: ldc.i4.2
IL_000f: callvirt instance void Demo.Numbers::Add(int32)
IL_0014: ldloc.2
IL_0015: ldc.i4.3
IL_0016: callvirt instance void Demo.Numbers::Add(int32)
IL_001b: ldloc.2
IL_001c: ldc.i4.4
IL_001d: callvirt instance void Demo.Numbers::Add(int32)
IL_0022: ldloc.2

C# 3.0 - Automatic Properties

Properties are widely used in .NET applications, but it’s also very common to declare their get/set accessors without any business logic, just with the minimum code to return and set the value of the property. Now it's possible to reduce the minimum code you need to type in order to have a property up and running.

Before automatic properties we needed to write:

private int count;
public int Count
{
    get { return count; }
    set { count = value; }
}

However, now you can do it as follows:

public int Count { get; set; }

The compiler will be in charge of declaring the private field that will be used as storage for the property value and the necessary methods to access/set the value.

I don’t see too many benefits in this feature from a developer perspective, with the “prop” code snippet you reduce even more the amount of code you need to type, in addition I really don’t like the syntax. I know it’s different but in my opinion it’s too similar to abstract properties or properties declared in interfaces. In fact, if you don’t add both, set and get, accessors you will get the error “must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors”. 

I understand that introducing new keywords in a language is always a pain for backwards compatibility, but in this case I would seriously consider adding something like “property”, in that way we could declare automatic properties like this:

public property int Count;

I think something similar is clear and reflects very good what it is ...

C# 3.0 - Extension Methods

Extension methods are a very cool feature. They are special static methods that can be used as if they were instance methods. What does it mean from our developer perspective? That we can simulate we add new methods to existing types.

It's quite common to find an existing class we want to extend with some new features. The alternatives to extend a class in this situation are limited, normally we will inherit from the class we want to extend, we will use a decorator pattern over it or we will embed the class in a wrapper. These techniques can be very useful, but sometimes they are not exactly what we really want to do.

Let's say you want a method that allows you to sort an array of int descending, the easiest approach you probably will use is to create a static method SortDesc that receives an int array as parameter and contains the logic to sort the array. Something similar to:

   1: static void Main(string[] args)
   2: {
   3: 
   4:     int[] numbers = new int[] { 1, 2, 3, 4, 5, 6 };
   5: 
   6:     SortDesc(numbers);
   7: 
   8:     foreach (int number in numbers)
   9:     {
  10:         System.Diagnostics.Debug.WriteLine(number);
  11:     }
  12: }
  13: 
  14: public static void SortDesc(int[] numbers)
  15: {
  16:     if (numbers != null && numbers.Length > 1)
  17:     {
  18:         bool sorted;
  19:         do
  20:         {
  21:             sorted = true;
  22:             for (int i = 0; i < numbers.Length; i++)
  23:             {
  24:                 if (i < numbers.Length - 1 && numbers[i] < numbers[i + 1])
  25:                 {
  26:                     int tmp = numbers[i];
  27:                     numbers[i] = numbers[i + 1];
  28:                     numbers[i + 1] = tmp;
  29: 
  30:                     sorted = false;
  31:                 }
  32:             }
  33:         } while (!sorted);
  34:     }
  35: }

With extension methods, we can rewrite the code in a way that the call to SortDesc is done as any other method of the class int[], like GetLength or GetLongLength. To do it we need we just need to apply the right syntax.

To declare an extension method we need include them in a static class, to specify the type we are going to extend we should set the modifier "this" before the first parameter of the method, being the type of the first parameter the type we are extending, in our case int[]. Once this is done we only need to import the namespace where we have created the static class, and all the int[] variables we use in the context will benefit of our new SortDesc method, and the coolest thing is that we will have intellisense for them. Look the code below.

   1: using Blog.Utilities;
   2: 
   3: static void Main(string[] args)
   4: {
   5:     int[] numbers = new int[] { 1, 2, 3, 4, 5, 6 };
   6: 
   7:     // New method invoke!!!
   8:     numbers.SortDesc();
   9: 
  10:     // Traditional method invoke!!!
  11:     Extensions.SortDesc(numbers);
  12: 
  13:     foreach (int number in numbers)
  14:     {
  15:         System.Diagnostics.Debug.WriteLine(number);
  16:     }
  17: }
  18: 
  19: namespace Blog.Utilities
  20: {
  21:     // Static class
  22:     public static class Extensions
  23:     {
  24:         // Note the "this" modifier before the parameter
  25:         public static void SortDesc(this int[] numbers)
  26:         {
  27:             // Method body
  28:         }
  29:     }
  30: }

If you look the line 11 you can see that the old syntax can be used to invoke the method, in fact the IL code generated proves that the compiler just translates the new invocation to the old one.

IL_0013: ldloc.0
IL_0014: call void Blog.Utilities.Extensions::SortDesc(int32[])
IL_0019: nop
IL_001a: ldloc.0
IL_001b: call void Blog.Utilities.Extensions::SortDesc(int32[])

The last thing we must know about Extension Methods is that their visibility is lower than instance methods, this means that if we have an instance method and an extension method, with the same parameters for the same type, the instance method will have preference over the extended one.

C# 3.0 - Implicitly Typed local variables

C# 3.0 introduces a new way to declare variables where the type applied can be inferred from the initializing expression. This is done using the keyword "var" instead of specifying explicitly the type. For example:

var text = "hello world" // type: string

var index = 12; // type: Int32

var people = new List(); // type: List

If you see the examples above you could think that the type used is a type variant or object, or any other type that encapsulates the real one. It is very important to understand that this is a wrong supposition. You can easily check that C# stills being a strong typed language, just adding the line "text = index;" to the examples above and tyring to compile. This will give you a compilation time error saying "Cannot implicitly convert type 'int' to 'string'", because text has been effectively declared as a string variable.

The easiest way to understand what it happens is considering the "var" keyword just as a token, which the compiler will replace by the real type and will produce exactly the same IL code as it we declare the variables using the traditional syntax. Let's take a look to the IL that the next C# code will produce:

var text1 = "hello world";

string text2 = "hello world";

.locals init ([0] string text1,
[1] string text2)
IL_0000: ldstr "hello world"
IL_0005: stloc.0
IL_0006: ldstr "hello world"
IL_000b: stloc.1

As you can see the IL that declares and initialize text1 and text2 is exactly the same.

I've seen some other posts that talk about the benefits of this new syntax, since cleans the code and avoids us writing the type two times, which is redundant in declarations like "List people = new List();". This is true, but doesn't mean that we have a "go on" to use it in all our variable declarations. It has no sense to use it when we do something like "int index = 12;", because we don't avoid writing a single char and just makes the code a bit less readable.

In the next posts we will see where this feature is really useful.