.NET, C#, Extension methods

C# 3.0 Extension Methods


One of the new features in .NET 3.5 and C# 3.0 is extension methods. Extension methods, as their names state, let you extend any existing type by adding new methods without having to inherit from it.

For instance, one of the common issues we encounter when retrieving data from the database, is to check whether the value is DBNULL or not before we can use it. I used to write a DbReaderHelper class that actually implements ‘dbnull safe’ data retrieval methods. The syntax to declare an extension method is very simple. It is a static method which its first argument starts with the keyword “this” followed by the type we want to extend.

For instance, if I want to add a new method called “nGetInt32” which returns an Int32.MinValue if the field is dbnull otherwise the field value (an Int32), I should write it as follows:

 

public static Int32 nGetInt32(this DbDataReader reader, int index)
{
      if (reader.IsDBNull(index))         
         
return Int32.MinValue;
      
     
return reader.GetInt32(index);
}

How to use it?

The extension must be part of a static class (see the example at the end of this post). To use it, simply add the namespace the class belongs to as part of the “using” directives and that’s it. Even intellisense will take it into account;

extension-method.png

 

Why using extension methods

If we want to extend the DataReader class to make it dbnull safe, we would have to inherit from one of its implementations and therefore would not be able to extend all inherited classes. The other advantage is the fact that you can extend any class (even those marked as “sealed”. On the other hand, extending a class has a limitation which is that the extension method can only use public methods and therefore there’s no access to the inner state of the object. 

Methods resolution 

          Instance methods have priority
          If the same extension method is declared more than once, the compiler raises an error.
          The compiler looks into the current namespace and all the namespaces included with the using directive. 

 

Advertisements
.NET, Anonymous types, C#

C# 3.0 Anonymous types


With C# 3.0 you can declare a variable without typing it explicitly and its type will be inferred based on the right expression. This is different from the non typing in VB like languages (ASP, VB) as the resulting value is really typed and can no longer be assigned to a different type. Also, right after entering the line that declares the variable, intellisense becomes available.

Intellisense

We can see that actually the variable x is of an anonymous type with the two properties Name and EmployeeNumber plus the inherited properties from the Object class. If we declare another anonymous type variable with the same structure: 

var y = new { Name = “Smith”, EmployeeNumber = “199283” }; 

Then the new variable, y, is compatible with x. In another words, since it has the same properties with the same types (string, string) then C# compiler detects that x and y are of the same type even though we never declared it explicitly. In this case the instruction: x  = y is correct and will result in affecting the value of y in x. However if we declare a third variable z:   

var z = new { Name = “Buddy”, Company = “Microsoft” }; 

and try to affect the value of z to x for instance, we will have a compilation error (and not a runtime error – typical for non-typed variables – ). Even though z has two members of string type, all like x and y, it is not compatible. The reason is that the second property has not the same name (company versus EmployeeNumber). 

Some restrictions to anonymous types:

Anonymous types are only permitted for local variables. You cannot declare a class member with the var keyword. A method cannot return a var type neither can it has a var type parameter; all the following declarations won’t compile: 

public int function(var x, int y)
public var function(int x, int y)

however returning a var variable value is permitted:  

public int function(int x, int y)       
{
           
  var t = x + y;
           
     return t;       
}

The reason is simple : at the point of the ‘return’ statement, the compiler knows that ‘t’ is an integer and can be returned since the method must return an integer. 

Why using anonymous types?

First, let’s calm down the spirits who think that this is a step back to untyped variables. As mentioned in this post, it is really an implicit typing and if you look at it closely, the variables are typed but the type is constructed ‘on the fly’ if we want. We can use it without declaring it. 

This may open the door to poor programming if it is overused. However, the impact might be limited since the anonymous type has only the scope of the method where it is used.  The main advantage of the anonymous types is in LINQ (beyond the scope of this post). I will post something on LINQ pretty quickly… 

Well the only advantage I can see is to be able to manipulate temporary results in a collection of an anonymous structure and then do something with it without having to declare a very lightweight structure or class just to carry the results in one single method. I can see the usage in a data access layer class that has to process the result returned by a DataReader. But until today, we lived without it and never felt really a need for it. 

As a conclusion, I believe that the real advantage is the LINQ query…. Which I will talk about in my next post.