Errr, some catchy title.... RSS 2.0
 Tuesday, January 23, 2007
Using Extension Methods with C# 3.0 and Orcas

I finally got around to play with January CTP release of Orcas (which is a codename for Visual Studio 2007). The first thing I wanted to try out are Extension Methods which are a new feature in C# 3.0 and VB 9.0 (and are included in .NET Framework 3.5).

 

Intro

 

So what are those Extension Methods?

 

In short: Extension Methods are static methods that are invoked with instance method syntax.

 

Why would I be interested in using them?

 

Well, they make your life easier. Isn’t that what it’s all about? J.

 

How to use it?

 

If you want to write a class that implements Extension Method, you must make it static. Furthermore the method must be static. Take a look at the code below:

 

public static class FirstExtension

   {

    public static int ToInt(this string target)

    {

    return Convert.ToInt32(target);

}

   }

 

 

Notice the keyword this in the method parameter. This indicates to the compiler (and IntelliSense) that this is an Extension Method. As you can see, the method takes in as a parameter a string and converts it into an integer. So one way of calling that method is:

 

string temp = "5";

int t = FirstExtension.ToInt(temp);

 

Nothing original here, but take a look at that:

 

string temp = "5";

int t = temp.ToInt();

               

 

So what exactly happened here? We created an instance of string object and we called a ToInt static method of class FirstExtension. So, as noted before this is nothing original, it just helps the developer to spend his time more productive.

 

 

There are a couple of things to consider:

  • Instance methods have always priority over Extension Methods.
  • It works with IntelliSense!
  • Checking for available Extension Methods is based on using / imports directive.
  • Currently, only Extension Methods are supported, properties, events and operators are currently being considered.

 

Usage

 

What I generally like about Extension Methods is the fact, that I’ll be able to write myself a Class Library, which will make my life easier. The first example provider is a great helper, because when you’re using DropDownLists and such, you always put the ID of the field in the Value and the Description in the Text.

Sooner or later you’ll have to convert the ID from string back to int. This extension will make the code more readable (and less writing for meJ).

 

Here are few other examples of the top of my head:

 

public static class CollectionHelper

    {

        public static void Consolize<T>(this IEnumerable<T> enumerable)

        {

            foreach(T ob in enumerable)

            {

                Console.WriteLine(ob.ToString());

            }

        }

    }

 

Usage:

 

Will iterate through whole collection and print out all objects to console.

string[] names = { "Burke", "Connor", "Frank",

"Everett", "Albert", "George",

"Harris", "David" };

 

names.Consolize();

 

Or another one:

 

public static class LogExt

{

public static void LogIt(this object ob)

{

Logger.Write(ob);

}

}

 

This will simply log all the data from the object (if you have overwritten ToString).

 

Note:

 

If you’re using Orcas January CTP and you copy pasted the code above you’ll get this exception:

 

Cannot use 'this' modifier on first parameter of method declaration without a reference to System.Core.dll. Add a reference to System.Core.dll or remove 'this' modifier from the method declaration

 

Simply add reference to System.Core.dll which is located in:

C:\WINDOWS\Microsoft.NET\Framework\v3.5.11209\System.Core.dll

Tuesday, January 23, 2007 1:15:38 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C# 3.0 | Orcas
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Marcin Waligora
Sign In
All Content © 2008, Marcin Waligora
DasBlog theme 'Business' created by Christoph De Baene (delarou)