What is the extension method in C# and how to use them? Explain with an example.
What is the extension method in C# and how to use them? Explain with an example.
494
14-Apr-2023
Updated on 15-Jun-2023
Aryan Kumar
15-Jun-2023Sure. Extension methods are a way to add new methods to existing types without having to inherit from them or modify them. Extension methods are declared in static classes, and they are called using the dot notation, as if they were instance methods.
To use an extension method, you first need to add a using directive to your code that imports the namespace that contains the extension method. Then, you can call the extension method as if it were an instance method on the type that it is defined for.
Here is an example of an extension method that converts a string to uppercase:
C#
To use this extension method, you would first need to add a using directive to your code that imports the namespace that contains the extension method. Then, you could call the extension method as follows:
C#
This would print the following output:
Code snippet
Extension methods can be a very powerful way to add new functionality to existing types without having to modify them. They can be used to simplify code, and they can make code more readable and maintainable.
Here are some of the benefits of using extension methods:
Here are some of the limitations of using extension methods: