What are extension methods? When do you use them?

  • Extension methods help extending types without altering them
  • They're particularly useful for extending classes which are sealed
  • They're created as static methods inside static classes
  • The first parameter of the extension methods is the type for which the method is to extend.
  • If the return type of the extension method is the type they're extending, then the methods can be chained together.
public class MyClass {
  /// 
}

public static MyClassExtensions {
  public static MyClass DoExtended(this MyClass obj, int someparam1, int someparam2.. )
  {
      // do something
      return obj;
  }
}


MyClass obj = new MyClass();
obj.DoExtended(); // this works although DoExtended is not a part of MyClass
  • Extension methods help extending types without altering them
  • They’re particularly useful for extending classes which are sealed
  • They’re created as static methods inside static classes
  • The first parameter of the extension methods is the type for which the method is to extend.
  • If the return type of the extension method is the type they’re extending, then the methods can be chained together.
public class MyClass {
  /// 
}

public static MyClassExtensions {
  public static MyClass DoExtended(this MyClass obj, int someparam1, int someparam2.. )
  {
      // do something
      return obj;
  }
}


MyClass obj = new MyClass();
obj.DoExtended(); // this works although DoExtended is not a part of MyClass

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *