Extension method is a feature of C# 3.0. The extension method helps to add method in existing class without modifying the source code or without inheriting the class. It achieves to add a new methods in the class even source code is not available means you had referenced the DLL of code in your project and want to add a new method into that.
For an example - you can add a new method in existing dotnet base classes and excess the same method in your coding whenever required. You may add a new method also in your defined classes which you had created earlier and without impacting the source code of the class you want to add a new method into that.
Extension methods are special kind of static method which must be written in static class where the first parameter helps to compiler and make clear that this class is going to be extend with a new method and this method will be accessible too through instance of extended class.
Extension methods are special kind of static method which must be written in static class where the first parameter helps to compiler and make clear that this class is going to be extend with a new method and this method will be accessible too through instance of extended class.
When to use Extension Method -
1. You cannot modify the source code of the class as you don't have source code. Eg - you had referenced DLLs.
2. When you don't want to modify the class as it seems to risky to modify the original class then better to add a new method in the class using a extension method.
Restriction in Implementing Extension Method -
Restriction in Implementing Extension Method -
1. When you extend a method then you had given the same name and signature which exists in extended class then it will be never called. Avoid to give the same name and signature, method signature should be identical.
2. Extension methods not meant to override the existing method. It promotes to add a new method in existing types.
3. The Fields, Properties and Events cannot be added only it supports to new methods.
4. Extension method must be static and should be written in a static class.
4. Extension method must be static and should be written in a static class.