#807 – Defining and Using an Extension Method

An extension method is a method that you define to extend an existing class without having to modify or inherit from the existing class.  The new method behaves as if it was defined as an instance method of the original class.

For example, you might define a Decorate() method that extends the System.String class.

To define an extension method:

  • Define it in a static class, as a static function
  • The 1st parameter must be of the type that you are extending and must include the this keyword on the parameter
    static class StringExtensions
    {
        public static string Decorate(this string s)
        {
            return "** " + s + " **";
        }
    }

You can now use the extension method as if it was an instance method on the System.String class.

            string s = "Fire at the triangle factory";
            Console.WriteLine(s.Decorate());

807-001

Advertisements