One cool feature that I found useful in C# are the so called Extension Methods. So what are Extension Methods you say ? Extension methods are in simple terms allows you to extend an existing type with additional functionality without having to modify the the old type.
Let’s say you have a program that have a series of methods related to string manipulations. So the common thing to do is to put all your string manipulation methods in a single class which we can call MyUtilities class:
Then here is a sample snippet in using the MyUtilities class:
We are expecting the results to be:
Applying the concept of Extension Methods you can easily integrate your string related manipulations to the string type itself without modifying it.
Here is a sample snippet for MyExtensionMethods class:
Using the MyExtensionMethods in the MainProgram:
Still we get the same results from our previous example using the MyUtilities class:
Things to keep in mind while using Extension Methods, It would be a good practice to store it in a separate source file such as MyExtensionMethods.cs.
Extension Method class should be declared as static class with a public access modifier so that it can easily be consumed.
Another thing to keep in mind is that every Extension Methods should contain the keyword this in order for the compiler to distinguish it as an Extension Method.