Hello friends, In this tutorial, we are going to learn the Extension method in C#. Extension methods as the name suggest are an additional method that is used to add additional functionality to an existing type without altering.
Extension method in C#::
Suppose you want to add additional functionality without modifying or recompiling or modifying the original class, the interface then Extension method enables you for the same. The Extension method was introduced with C# 3.0. The Extension method is a static method to an existing static class. If you are familiar with ASP.NET MVC then the best example of Extension methods are HTMLHelper extensions.
Point to be Remember:
- It is a static method.
- It must be declared within a static class.
- The first parameter of the extension method must be of the type for which the extension method is applicable, preceded by this keyword.
- It uses this keyword as the first parameter with a type for which extension method is applicable.
- Extension methods cannot be used to override existing methods.
- The concept of extension methods cannot be applied to fields, properties or events.
- Overuse of extension methods is not a good style of programming.
Example of the Extension method on String Type:
The following example shows an extension method defined for the System.String class.
Example of Extension method on Integer Type:
- DirectoryInfo class in C#
- Sealed class in C#.
- C# Program to find the sum of all item of an Integer Array.
- C# Program to Convert Number to Word.
I hope you would love this post. Please don’t hesitate to comment for any technical help. Your feedback and suggestion are important to me.