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
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.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.