Muhammad Ali Khan

MS CRM 3.0, MS CRM 4.0, Sharepoint 2007 & Sharepoint 2010

Extension methods in C# 3.0

Posted by Ali Khan on September 19, 2007

Extension methods are static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods

Declaration:

Extension methods are declared by specifying the keyword this as a modifier on the first parameter of the methods. Extension methods can only be declared in static classes. The following is an example of a static class that declares two extension methods:

namespace MyUtilities
{
      public static class Extensions
      {
            public static int ToInt32(this string s) {
                  return Int32.Parse(s);
            }

            public static T[] Slice<T>(this T[] source, int index, int count) {
                  if (index < 0 || count < 0 || source.Length – index < count)
                        throw new ArgumentException();
                  T[] result = new T[count];
                  Array.Copy(source, index, result, 0, count);
                  return result;
            }
      }
}

Extension methods have all the capabilities of regular static methods. In addition, once imported, extension methods can be invoked using instance method syntax

Importing & Using extension methods:

Extension methods are imported through using-namespace-directives (§9.3.2). In addition to importing the types contained in a namespace, a using-namespace-directive imports all extension methods in all static classes in the namespace. In effect, imported extension methods appear as additional methods on the types that are given by their first parameter and have lower precedence than regular instance methods. For example, when the MyUtilities namespace from the example above is imported with the using-namespace-directive

using MyUtilities;

it becomes possible to invoke the extension methods in the static class Extensions using instance method syntax:

string s = “1234”;
int i = s.ToInt32();                            // Same as Extensions.ToInt32(s)

int[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] a = digits.Slice(4, 3);       // Same as Extensions.Slice(digits, 4, 3)

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: