What are extension methods

Extension methods are a powerful feature in C# that allow you to add new methods to existing types without modifying their source code. This is particularly useful for enhancing a type provided by a third party or when you want to add utility methods to all aspects of an existing object type.

To create an extension method, you define a static method in a static class, and the first parameter of the method must use the `this` keyword followed by the type you want to extend. Once defined, these methods can be called as if they were instance methods on the extended type.

Here's an example of how to create and use an extension method:

public static class StringExtensions { public static int WordCount(this string str) { return string.IsNullOrWhiteSpace(str) ? 0 : str.Split(' ').Length; } } // Usage string example = "Hello world"; int count = example.WordCount();

keywords: extension methods C# programming software development .NET