Extending .NET Framework 3.5

Published:
Extention Methods in C# 3.0

by Ivo Stoykov

C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance.

These are static methods invoked as instance method. This allows developers to add functionality without necessity to create derived types, re-compiling or other modifications of existing objects. Also to extend sealed objects and avoiding deep digging into object inheritance tree.

Declaration

There are few "must do" in extension method declaration

1. Must be declared into static class
2. Method must be static
3. 1st parameter must be this.

This first parameter in method declaration is the most important one. It specifies witch type the method operates on. The keyword this defines that method is applied on the instance of defined type.

In the sample below we have only one parameter compound by three parts. Part one is the keyword stating that the method WordCount is applicable to String type.

Part two is the type itself -- String in our sample.

Part three is the particular instance of the type the method will be executed -- in the sample this is property name s. In other words the method will be applicable to any String instance.

In the sample we define in Main method a variable of String type named str. In the next row we use standard notation -- type, dot, method, parameters -- str type on the left of the dot becomes out first parameter in WordCount method and, so str becomes s representing String instance passed as this.

This is why extension methods might appear anywhere (same as in the sample or any other file; same or any other project) and will be available all the time if their namespace is explicitly imported into source code with a using directive.


What Extension Method Cannot do

* Extension methods cannot be used to override existing methods
* An extension method with the same name and signature as an instance method will not be called
* The concept of extension methods cannot be applied to fields, properties or events


// Program.cs
                      using System;
                      using System.Collections.Generic;
                      using System.Linq;
                      using System.Text;
 
                      namespace ExtensionMethodTest
                      {
                        static class StrExt
                        {
                          public static int WordCount(this String s)
                          {
                            return s.Split(new char[] {'\t', ' ', ',', '.', '?', '!', ';', ':'}, StringSplitOptions.RemoveEmptyEntries).Length;
                          }
                        }
 
                        class Program
                        {
                          static void Main(string[] args)
                          {
                            String str = "This string! has; few words! This is, shoerter.";
 
                            Console.WriteLine("string " + str + Environment.NewLine + "has " + str.WordCount() + " words");
                          }
                        }
                      }

Open in new window

0
4,161 Views

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.