views:

117

answers:

7

Duplicate

What are Extension Methods?
Usage of Extension Methods
What Advantages of Extension Methods have you found?

So I run into the term "extension-methods" frequently, when reading about .Net and intellisensing (!) around...

What are extension-methods -- and what sets them apart from other methods?

+2  A: 

They're static methods that can be added to other types without modifying the original type.

For example, say you want to be able to call ToInt() on a string. You can create a method like this:

public static int ToInt( this string value ){ return Int32.Parse( value ); }

Now say you have a TextBox called Port on your web page you can get it as an int like this:

int port = Port.Text.ToInt();

Real world use of extension methods is usually much more useful then that and is used heavily by Fluent APIs and testing frameworks.

UPDATE: Another good use of extensions is to provide base class like default behaviors for interfaces. Many popular testing methodologies depend on interface definitions and the ability to mock those interfaces. Unfortunately, basing everything on interfaces however loses some of the benefits of inheritance. Extension methods can add some of the convenience of base classes without the pollution of the interfaces.

For example say I have a Window base class defined like this

public class Window
{
    public void Show( object owner ){...}
    public void Show(){ Show( null ); }
}

Now I want to extract an IWindow interface from this class. I don't really want to require every object that derives from IWindow to have to implement the second Show method since it's just a basic overload. So I can define my interface like this:

public interface IWindow
{
    void Show( object owner );
}

And an extension method like this:

public static void Show( this IWindow window )
{
    window.Show( null );
}
Paul Alexander
A: 

See the MSDN Topic on extension methods

Jimmie R. Houts
A: 

Extension methods are static methods in your own class that you can use to manipulate types, typically not in your own code.

For example, you can write:

public static void RemoveS(this string value)
{
   value = value.Trim("s");
}

And this method will be appended to all "string" types in your system, so long as the namespace where you wrote it is available to the compiler.

Like:

string foo = "Somethings";
string betterfoo = foo.RemoveS();

See: http://www.csharphelp.com/archives/archive148.html for more help.

JasonW
A: 

I wrote a summary about them here:

http://blogs.msdn.com/vbteam/archive/2007/01/05/extension-methods-part-1.aspx

Back when I used to work on the VB compiler team. It gives a good overview of why they are useful.

Scott Wisniewski
A: 

Extension Methods are methods you create to EXTEND an already existing type (string, int, char, or custom type).

This allows you to add functionality to built-in or types created by others (in a dll for example).

JTA
A: 

Extension methods a static functions that are added to static classes that the compiler can allow you to expose as an instance method on ANOTHER type. For example, say I wanted to add a function called "MakeInvisible()" to the Control class that could, well, make it invisible (ignoring the fact that such a method already exists in "Hide()"...). I would do it like this.

public static class ControlExtensionClass
{
    public static void MakeInvisible(this Control control)
    {
        control.Visible = false;
    }
}

If I have this class somewhere in my referenced assemblies, I can then do this anywhere..

Control c;

c.MakeInvisible();

The 'this' keyword is what makes this an extension method. This tells the compiler to add this method to the Control class, and provide a reference to the entity in the specified variable.

Adam Robinson
+1  A: 

Extension methods are static method with a special syntax for the first parameter. The compiler allows you to use them syntactialy like instance methods.

public class ExampleClass
{
   public String Value { get; set; }
}

Now you could introduce a method PrintValue() by modifying the class.

public class ExampleClass
{
   public String Value { get; set; }

   public void PrintValueInstance()
   {
      Console.WriteLine(this.Value);
   }
}

You could also create a static method in some class - ExampleClass or any other.

public class AnyClass
{
   public static void PrintValueStatic(ExampleClass exampleClass)
   {
      Console.WriteLine(exampleClass.Value);
   }
}

And you can create an extension method - it's much like the static method, but marks the first parameter with this.

public class ExtensionClass
{
   public static void PrintValueExtension(this ExampleClass exampleClass)
   {
      Console.WriteLine(exampleClass.Value);
   }
}

The ussage is then as follows.

ExampleClass example = new ExampleClass();

example.PrintValueInstance(); // Instance method

AnyClass.PrintValueStatic(example); // Static method

ExtensionClass.PrintValueExtension(example); // Extension method (long usage)

example.PrintValueExtension(); // Extension method

So the compiler allows you to use a static method with instance method syntax on objects that match the type of the first parameter. This allows you to add methods to a class without the need to modify the class. Of course, there is a limitation - you can only access public members from within a extension method.

You can also define extension methods for interfaces and they are then availiable to all classes implementing the interface.

public interface ISomeInterface
{
   Int32 Foo(Int32 value);
   Int32 Bar(String text);
}

public static class SomeInterfaceExtension
{
    public static Int32 FooFooBar(this ISomeInterface @this, String text)
    {
       return  @this.Foo(@this.Foo(@this.Bar(text));
    }
}

Now the method FooFooBar() is availiable on all classes implementing ISomeInterface.

public class NiceClass : ISomeInterface
{
   public Int32 Foo(Int32 value)
   {
      return value * value;
   }

   public Int32 Bar(String text)
   {
      return text.Length;
   }
}

Now you can use the extension method on NiceClass instance.

NiceClass niceClass = new NiceClass();

Console.WriteLine(niceClass.FooFooBar("ExtensionMethodExample"));
Daniel Brückner