As name implies extension methods allow existing classes to be extended without using inheritance or changing class’s source code.
Some important points when using extension methods:
• You cannot use extension methods to override existing methods
• An extension method with the same name and signature as an instance method must not be called
• The concept must not be applied to fields, properties or events
• Do not overuse
As an example, we’ll create an extension method to existing ‘String’ class. We’ll implement the functionality of converting a string to a proper case. (Any given string will be converted to lower case, having the first letter of each word in upper case. E.g.: ‘this is sample text’ will be converted to ‘This Is Sample Text’)
Add a class and add the following code:
please note that the class that the class should be static and the method should be public (Unless you are writing it within the same calss which you intend to use it). And also in input the parameter I have mentioned 'this'. This will tell the compiler to add the following method to the 'String' class.
Before using include the namspace. (I have used 'ExtensionMethods' as the namespace)
And you can use the method we created using this syntax :
And if you run the application you can get the below output (I have used a console application to illustrate this)