Sometimes there is a need to add customized/ user defined methods to existing datatypes. If we write String s1 and then put a dot after s1, we get a list of methods pre-defined such as Aggregate<>, All<>, Average<> etc. With extension methods, we can write out our own method that can be used with existing datatypes as an extension. Sample: Step 1: Create a Console Application Step 2: Create an ExtensionClass as
using System; using System.Collections.Generic; using System.Linq; using System.Text;
/* Class to display Extension Method */ namespace DeeptendraSpace { public static class ExtensionClass { //**********//Extension Method//**************// //Sample Extension Method 1 public static string ShowMethod(this string val) { return "Hello :" + val; }
public static void AddMethod(this int x, int y) { Console.WriteLine(x + y); }
} } Step3: In main method, write the following. class Program { static void Main(string[] args) { String msg = "Deep"; Console.WriteLine("//********Extension Methods**********//"); Console.WriteLine(msg.ShowMethod()); // Calling Extension Method1 msg.ShowMethod() int a, b; a = 1; b = 2; a.AddMethod(b); //Calling Extension Method2 a.AddMethod(b) Console.ReadKey(); } }
Clearly we can see that the string msg, and integer a are calling extension methods from the ExtensionClass.
Balaji M Kundalam edited Revision 1. Comment: Typography - minor correction
This article may benefit from See Also section and more complex explanations and examples. Say, you may want to show an Extension method for Generic class
Ed Price - MSFT edited Revision 5. Comment: Font style; tags