Wednesday, February 13, 2008

C# 3.0 Explained: Extension Methods

Extension methods are static methods that extend the existing types and constructed types with additional methods. They offer a solution to situations where inheritance is not possible. Extension methods are declared by specifying the this keyword on the first parameter of the methods. Let's see an example.

Say you want to create a wrapper method to find the difference between two dates in days. You would probably create a static method that takes two dates and returns the difference. With the help of Extension methods, you can implement this feature directly into the DateTime structure.
See the code below:

namespace SeeSharpOverview.Version3
{

static class DateTimeExtender
{

public static int DifferenceInDays(this DateTime start, DateTime end)
{
return (end - start).Days;
}

}

}

Extension methods exist in static classes only. In addition, the static class should be non-generic.
Notice the this keyword used on the first parameter of DifferenceInDays. This means that the DateTime structure would be extended to include this method.

In order to use this extension method, I'd have to import the namespace SeeSharOverview.Version3. By importing the namespace, i could use all the extension methods existing inside that namespace.

using SeeSharpOverview.Version3;

DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(2);

int days = date1.DifferenceInDays(date2);

System.Console.WriteLine(days);

The above code would output: 2, meaning difference in days is 2.

Extension Methods behave like normal static methods. Therefore, DateTimeExtender.DifferenceInDays(date1, date2) works just fine. Notice though, when using with the instance variable date1, the method takes only 1 argument.

Remember while implementing Extension Methods:
  • A method M with the same signature to that of an Extension Method in a type has higher priority than the Extension Method. This mean, the method M will be called not the Extension Method.

General Guidelines to using Extension Methods:
  • Should be used sparingly and only when needed
  • Should not be preferred over inheritance , where inheritance is possible
Lamda Expressions are next.

Monday, February 11, 2008

C# 3.0: Explained: Implicitly Typed Local Variables

C# 3.0 brings lots of new extensions C# 2.0. The extensions are:

  • Implicitly typed local variables
  • Extension methods
  • Lamda Expressions
  • Object initializers
  • Anonymous Types
  • Implicitly typed arrays
  • Query Expressions
  • Expression Trees
Download the Official C# 3.0 Language Specification from Microsoft.

I will do my best to cover all of these advanced topics.

Implicitly typed local variables

Implicitly typed local variables are automatically inferred by compiler to their corresponding strong types.

var name = "Hemanta Sapkota";
var id = new string[] { "1", "2" };
var myList = new List<string>();

Notice the var keyword is used. Remember the above is same as doing:

string name = "Hemanta Sapkota";
string[] id = new string[] { "1", "2" };
List<string> myList = new List<string>();

The code below illustrates common correct use and restrictions to using implicitly typed local variables.

class Program
{

var notLegal; //Error. Cannot declare non-local var

static
void Main(string[] args)
{
//correct use
var name = "Hemanta Sapkota";
var id = new string[] { "1", "2" };
var myList = new List<string>();
var var = 32; //creating a variable with the name 'var' is allowed

var = 45; //here 'var' refers to the var type we created above. This is allowed.

//Error.
var l1 = "name", l2 = "none"; //cannot have multiple declarators
var col = { 'a', 'b', 'c' }; //Collection initializer not permitted
var notNull = null; //Cannot assign to an implicitly-typed local variable
var alsoNotLegal; //Implicitly-typed local variables must be initialized
alsoNotLegal = String.Empty;

var v1 = "taxi";
var v2 = 45.6;
v1 = v2 = "error"; //cannot implicitly convert type 'string' to 'double'

}

}

Implcitly typed local variables can also be used with for-initializer, and foreach. Consider:

var myList = new List<string>();

myList.Add("Item1");
myList.Add("Item2");
myList.Add("Item3");

foreach (var str in myList)
{
System.Console.WriteLine(str);
}

Likewise implicitly typed local variables can also be used with the using statement.
In the next post, i will talk about Extension Methods.