What Are Extension Methods?

Learn how to write extension methods.

We need extension methods because LINQ uses extensions methods on the IEnumerable type. And, we’ll likely find extension methods handy outside this course too.

We can add new methods to a type without modifying it with extension methods. They are static methods defined outside the declaration of a type. But we use extension methods the same way we use typical methods: an object reference, a . dot, and the method name.

How to write extensions methods

Class declarations

First, we need to create a static class to create extension methods. By convention, we name this class after the object we want to extend, followed by the suffix Extensions.

For example, we can write extension methods for the built-in String class in a new StringExtensions static class.

Get hands-on with 1200+ tech skills courses.