An extension method in C# allows you to extend the functionality of an existing type without modifying its source code. This is accomplished by defining a static method with a special syntax in a separate class. The method will appear as if it were a part of the original type, giving you the ability to extend its functionality as if it were part of the original class.
To create an extension method, you need to follow these steps:
Create a static class: The first step is to create a static class to hold your extension method. This class should have the same name as the type you want to extend, followed by the word “Extension”. For example, if you want to extend the System.String class, you would create a class named “StringExtension”.
Add a static method: Next, you need to add a static method to your class. The method should have the same name as the type you want to extend, followed by a dot (.) and the name of your extension method. For example, if you want to extend the System.String class with a method called “ToTitleCase”, you would create a static method named “String.ToTitleCase”.
Use the “this” keyword: To make your method an extension method, you need to use the “this” keyword followed by the type you want to extend as the first parameter of your method. For example, if you want to extend the System.String class, the first parameter of your method would be “this string str”.
Implement the functionality: Once you have created your method, you can implement the desired functionality. Your method should accept one or more parameters, as needed, and return a value or void.
Here’s an example of how you might create an extension method to convert a string to title case:
In this example, the output would be “Hello World”.
Extension methods are a powerful tool for extending the functionality of existing types in C#. They allow you to add new functionality to a type without modifying its source code, and they provide a way to extend the functionality of types that you don’t own or control. Whether you’re working with built-in types like System.String or custom types that you’ve created yourself, extension methods are a useful and flexible tool to have in your C# toolkit.