DCSIMG

 Subscribe in a reader

Extension Methods - Guy kolbis
Saturday, September 15, 2007 8:40 PM kolbis

Extension Methods

Extension methods is a new feature introduced by Orcas. As the name implies, the idea behind the extension method is to extend existing types with new methods.

Getting Started

Creating an extension method is fairly simple. For example, lets say that for each string type, you would like to add a new method that will convert white spaces into underscores:

        public static string SpaceToUnderscore(this string source)
        {
            char[] cArray = source.ToCharArray();
            string result = null;
            foreach (char c in cArray)
            {
                if (Char.IsWhiteSpace(c))
                    result += "_";
                else
                    result += c;
            }
            return result;
        }

For those of you with the sharp eyes, you might have noticed that the method must be declared as static and that the input parameter proceeds by the keyword "this". When doing so, we actually tell the compiler that this is an extension method for type string. Now, we can use the extension simply by adding a reference to the assembly where we defined it and adding the appropriate namespace.

            string str = "Extension methods overview by Guy Kolbis";
            str.SpaceToUnderscore();

Linq

My main motivation for exploring the extension method feature was another new feature named Linq. It all began by simply exploring the List<T> type.

            List<Person> people = new List<Person> 
            {
                new Person(){ ID = 1, IDRole = 1, LastName = "Anderson", FirstName = "Brad"},
                new Person(){ ID = 2, IDRole = 2, LastName = "Gray", FirstName = "Tom"}
            };

When I created a new list of type List<Person> I have noticed something strange. I could actually see several method signatures that originaly should not belong to the List<T> implementation:

image

The "Where", "Select" and others methods have been added to that type.

You may wonder how this is possible. C# 2.0 doesn’t provide these methods for the List<T> class. Moreover, LINQ runs on .NET 2.0 and installing LINQ doesn’t replace any .NET 2.0 assemblies.

So, after reading the fine prints I have noticed two things:

1) image - The Icon indicates an "extension method".

2) image - The documentation indicates that this is an extension method.

Now, lets go back to Linq. When we query an IEnumerable<T> we use enhancements to the C# languages, for example:

            var query = from p in people
                        where p.ID == 1
                        select new { p.FirstName, p.LastName };

When the compiler finds a query expression, it will convert it to method calls:

            var query = people.
                            Where(p=>p.ID == 1).
                            Select(p=>new {p.FirstName,p.LastName});

The from keyword has been removed, leaving just the collection, people, against which to perform the query. The where and select clauses are transformed into two method calls: Where<T>() and Select<T>(), respectively. They have been concatenated so that the Where method’s result is filtered by the Select method.

This would have not be possible without the extension methods.

תגים:, , ,

תוכן התגובה

# Lambda Expressions

Guy kolbis כתב/ה

Visual studio Orcas and C# 3.0 introduce some very cool features. Recently I have been working on several

Monday, September 17, 2007 10:29 AM

שלח תגובה

(שדה חובה) 
(שדה חובה) 
(אופציונלי)
(שדה חובה) 

Enter the numbers above: