Extension Methods - CSharp Custom Type

CSharp examples for Custom Type:Extension Methods

Introduction

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

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.

An extension method cannot be accessed unless its class is in scope.

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

For example:

public static class StringHelper
{
  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.

Demo Code

using System;/*from   www. ja v  a 2 s .c  o m*/
public static class StringHelper
{
   public static bool IsCapitalized (this string s)
   {
      if (string.IsNullOrEmpty(s)) return false;
      return char.IsUpper (s[0]);
   }
}
class Test
{
   static void Main()
   {
      Console.WriteLine ("asd".IsCapitalized());
   }
}

Result


Related Tutorials