Website Links

Friday, 1 September 2017

C# - Extension Methods

Extension methods allow you to extend functionality of a specific type. It is a special kind of static method that you can call as if it were an instance method on the object of the specified type. Extension methods are simple to define and you can define them as follows:

  using System;
     
  public class Program
  {
    public static void Main()
    {
      string message = "Hello World";
      Console.WriteLine(message.GetDatedMessage());
    }
  }

  // Extension methods must be contained within a non-generic static class
  public static class StringExtensions 
  {
    // Extension methods must be static
    // Extended object must be prefixed with this
    public static string GetDatedMessage(this string message) {
      return String.Format("{0}: {1}", DateTime.Now, message);
    }
  }

No comments:

Post a Comment