Extending DataContext using Extension methods

Extension methods are great as they allow you to extend any class within C# 3.0 with the instance of the class being passed in as a parameter. 

In C# 2.0 we had an initial way with partial classes which allows us to extend classes with our own custom logic, however it only worked if the other class was marked as partial.

I talked before how we can extend the DataContext created by the designer (NorthwindDataContext) by using partial classes,  however if we wanted a method on all of the DataContext object in our system, we would have to create a partial class for each of them separate. This would result in a lot of duplicate code and a maintenance nightmare.

partial class DataClasses1DataContext { //… }

partial class DataClasses2DataContext { //… }

The other solution would be to add a partial class to the DataContext and have it be inherited by the other objects in the system, however this doesn’t work as the DataContext class is not partial.

The answer is, Extension methods. Extension methods allow us to extend any object in the system, even if it is marked as sealed.  They require the following:

  • Be in their own public static class
  • Method be public static
  • use the ‘this’ keyword with the object we want to extend as the first parameter.  Other parameters can be added after this.
  • Accessible from the calling object.  If they are in there own namespace, the namespace needs to be referenced via a using directive.

Using this, we can extend the DataContext class and have all of our own DataContext’s in the system implement our new functionality.

The following code could be used and access any information from the DataContext as a parameter:

namespace MyExtension
    public static class Extension
        public static void PrintConnection(this DataContext dc)

This could then be accessed by any child object in the system like this:

DataClasses1DataContext db = new DataClasses1DataContext();

We are limited to the public interface of DataContext, but this is still a very useful technique. This also applies to any other object within .Net.

Technorati Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *