Skip to content

Extension Methods

Mario Gutierrez edited this page Jan 7, 2017 · 1 revision
  • Extension methods must be defined in a static class, and must be static.
  • These add methods to existing types.
  • The target type is specified as the first parameter.
  • Additional parameters are allowed.
using System.Reflection;

static class MyExtensions
{
  // Targeting the Rectangle type.
  public static bool IsSquare(this Rectangle r)
  {
    return r.Height == r.Width;
  }

  // Targeting the int type.
  public static int Add(this int a, int b)
  {
    return a + b;
  }

  // You can also define extension methods targeting interfaces.
  public static void PrintAll(this System.Collections.IEnumerable iterator)
  {
    foreach (var item in iterator)
    {
      Console.WriteLine(item);
    }
  }
}
int myInt = 30;
int result = myInt.Add(2); // Using an extension method from MyExtensions.
Clone this wiki locally