C# Extension Methods

Description

Extension methods can extend an existing type with new methods without altering the definition of the original type.

Syntax

An extension method is a static method of a static class, where the this modifier is applied to the first parameter.

The type of the first parameter will be the type that is extended.

Example

For example:


public static class StringHelper
{// w  w w  . j  ava2  s .c  o m
  public static bool IsCapitalized (this string s)
  {
    if (string.IsNullOrEmpty(s))
       return false;
    return char.IsUpper (s[0]);
  }
}

The IsCapitalized extension method can be called as though it were an instance method on a string, as follows:

Console.WriteLine ("Java2s".IsCapitalized());

An extension method call, when compiled, is translated back into an ordinary static method call:

Console.WriteLine (StringHelper.IsCapitalized ("Path"));

The translation works as follows:


     arg0.Method (arg1, arg2, ...);              // Extension method call
     StaticClass.Method (arg0, arg1, arg2, ...); // Static method call
     

Interfaces can be extended too:

   
public static T First<T> (this IEnumerable<T> sequence)
{/*w w w.ja va  2s .c o  m*/
  foreach (T element in sequence)
    return element;

  throw new InvalidOperationException ("No elements!");
}

Console.WriteLine ("Java2s".First());  

The code above generates the following result.

Note

Any compatible instance method will always take precedence over an extension method.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor