Outline

Extension Methods

What are Extension Methods?

Extension methods enable you to "add" methods to existing types without creating a new derived type or modifying the original type. There is no apparent difference between calling an extension method and the methods defined in the type.

Requirements

Extension methods are defined as static methods. The parameter is preceded by the "this" modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a "using" statement.

Consider the following codeā€¦

using System;
using System.Collections.Generic;

namespace Conduit.Models.Exceptions
{
    public static class ExceptionHelper
    {
        public static Dictionary<string, object> ToDictionary(this Exception ex)
        {
            var returnVal = new Dictionary<string, object>();
            returnVal.Add("message", ex.Message);
            return returnVal;
        }
    }
}

Just like any other class you still have:

  • using statements
  • A namespace
  • The class name with the optional "static" modifier
  • Along with a method

The method for the most part is normal:

  • Has a visibility modifier
  • A return type
  • The method name
  • But you'll notice that it requires
    • Static
    • "this" as part of the parameters
    • "this" represents the type

In this case, "Exception" is the type this method will extend. In the next video we'll put it together so that it makes more sense.

Resources:

  • https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods