C# Extension Methods

In this chapter you will learn:

  1. What are Extension Methods
  2. Syntax to create Extension Methods
  3. Example
  4. Extension methods versus instance 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
{/*from  www . j  av a 2  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)
{/*ww w  . ja  v a  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.

Next chapter...

What you will learn in the next chapter:

  1. What are C# Properties
  2. How to create C# Properties
  3. Example for C# Properties
  4. Note for properties
  5. Add statement to the getter and setter of a property
  6. Put logic to property setter
  7. throw Exception from property setting
Home »
  C# Tutorial »
    C# Types »
      C# Method
C# class method
C# method parameters
C# ref parameter
C# out parameter
C# named parameters
C# params parameters
C# Optional parameters
C# method overloading
Recursive methods
C# Return Statement
static method
C# Main Function
C# Extension Methods