C# provides a very useful feature to extend the feature of an existing type without requiring the source code of original data type or permission of author who created the original type. Use of extension method is very common and every application creates one or more extension methods based on thier custom requirement. We will see some of the easiest example of Extension methods and see how it's works.
Creating Extension methods is very straight forward and it's like creating a static class with static method and the first parameter of the method will have "this" keyword of C# language.
In the above example we can see that StringExtensions is a static class with a static method named Truncate with first parameter have this keyword before the data type string so basically this is a string extension method which is extending the feature of string data type and providing the truncate feature.
Once Extension method is created in the application we can C# compiler gives us intelli sense for the new extension method as well.
I have written the below unit test for the Truncate method to validate the same.
Above is the simple String Extension method and we can create any number of Extension method based on our requirements.
We can create extension method based on pre defined data type of C# language like int, String, Decimal, Dictionary etc..
Let's create another extension method based on String data type which will return numbers only from a given string.
Unit Test to validate NumbersOnly Extension Method
Hope you understood the Extension methods in C#
Share This Post