-2

Possible Duplicate:
What are Extension Methods?

Can someone explain what Extension Methods are in C# and how the work in layman's terms and if possible some examples please

Community
  • 1
  • 1
dennis
  • 1,077
  • 1
  • 8
  • 7

3 Answers3

1

Extension methods are syntactic sugar for static method calls.

The following are equivalent:

Extension:

public static int GetLength(this string s)
{
    return s.Length;
}

s.GetLength();

Static:

public static int GetLength(string s)
{
  return s.Length;
}

SomeClass.GetLength(s);
Femaref
  • 60,705
  • 7
  • 138
  • 176
0

In summary, Extension Method is syntax sugar, allowing to create a method in fact not belonging to type. Indeed, that's just a static method threated by compiler as a member "native".

Assuming you have a type:

class Test
{
    void Foo();
}

Let's declare an extension method:

static class Extensions
{
    public void Bar(this Foo) { }
}

Now you can call it:

new Test().Foo(); // "native" method
new Test().Bar(); // extension method

In fact that's just this:

public static void Bar(Test t) { }
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

I think you can already find enough references on this topic on the web, like this MSDN article.

In a nutshell, extension methods allow you to extend a class without deriving it. They are some particular static methods, belonging to a static class. They always start with a parameter of the type they extend, prefixed with the keyword this. Let's say you want a method to return the extension of a file from a string (hope the logic is right, didn't check it actually):

public static class FileExtension
{
    public static string Extension(this string filename)
    {
        int index = filename.LastIndexOf('.');
        if(index > 0)
            return filename.Substring(index, filename.length - index);

        return filename;
    }
}

And then you can say:

string filename = "c:\temp\sample.txt";
string ext = filename.Extension();
Marius Bancila
  • 16,053
  • 9
  • 49
  • 91