Jump to content

Extension method

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Bashmohandes (talk | contribs) at 00:15, 6 January 2007 (Created the article). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

Extension Methods

One of the features of C# 3.0

Problem

First let's consider the case we have a class, and we want to add extra function to it, so simply if we have the class code, we will edit that code and that's it, so what if this class is inside an assembly (dll) which we don't have the code, the solution will be one of two options,

  1. The first option is to inherit the class and add the function.
  2. The second option is to write the method we want to extend in a new class as a static method that takes an object of the class type and return a new object with the modification we want,

Current Solution

The first option sounds simpler, but actually it is harder, because sometimes you can't do this, because inheritance has some limitations, like you can't inherit a sealed class, or a primitive data type such as int, float, ... etc. Ok, we still have the second option, which is writing a class anywhere, and add the function to it as static function. However, you can't do something like this

  string x = "some string value";
  string y = x.Reverse();

which you can't use the function as if it is part of the class itself, and you will end up with code similar to this

  string x = "some string value";
  string y = Util.Reverse(x);

that's because you wrote the Reverse function the Util function.

Extension Methods

in C# 3.0 you can configure the Util.Reverse() function to make the first code doable, so consider the following code of Util.

  public static class Util
  {
     public static string Reverse(this string input)
     {
        char[] reversedChars = new char[input.Length];
        for (int i = input.Length - 1, j = 0; i >= 0; --i, j++)
        {
           reversedChars[j] = input[i ];
        }
        return new String(reversedChars);
     }
  }

as you can see it is a simple static class, with one static function called Reverse, all what we have to do

  1. Make sure that the class is static
  2. Add this keyword before the type of the argument you want to extend.

so now you can write this code,

  string x = "some string value";
  string y = x.Reverse()

Reference

Blogs