Extension methods enables you to add methods to existing types without creating a new derived type, recompiling or otherwise modifying the original type. Extension methods are special type of static methods, but they are called as if they are instance methods on the extended type. For client code written in C# or Visual Basic there is no apparent difference between calling an extension method and the methods that are actually defined in the type. Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using
directive. In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method. Therefore, the principle of encapsulation is not really being violated. In fact, extension methods cannot access private variables in the type they are extending.
Please find below an example of adding extension method to the string class.
namespace ExtenstionMethodDemo
{
class Program
{
static void Main(string[] args)
{
string name = "test String";
string result = name.ChangeFirstLetterCase();
Console.WriteLine(result);
}
}
}
namespace ExtenstionMethodDemo
{
public static class StringHelper
{
public static string ChangeFirstLetterCase(this string inputString)
{
if (inputString.Length > 0)
{
char[] charArray = inputString.ToCharArray();
charArray[0] = Char.IsUpper(charArray[0]) ? Char.ToLower(charArray[0]) : Char.ToUpper(charArray[0]);
return new string(charArray);
}
return inputString;
}
}
}