This is a new feature that has been inter choose in C#.Net 3.0 that allows us to add new methods into an existing class without editing the source code of the class.
Defining Extension:
- Extension methods must be defined under static class only so every extension method is static by default but once the method is bound with another class it gets converted into non static and it can be called by using old classes object.
- The first parameter of an extension method is to specify to which class the method has to be bound with and we call it as a binding parameter which should be defined as following.
this<class name><obj>
- If required we can also pass normal parameters to an extension method which should start from the second place of parameter list and all this parameter will be considered while calling the method.
- If an extension method is defined with n parameters while calling the methods we will be having n-1 parameters only because binding parameters is excluded.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpConsole { class oldclass { public int a; public oldclass (int a) { this.a=a; } public void show1() { Console.WriteLine("Method One: " + this.a); } public void show2() { Console.WriteLine("Method Two: " + this.a); } } } // Now add a newclass.cs and code the following using System; namespace CSharpConsole { static class newclass { public static void show3(this oldclass obj) { Console.WriteLine("Method three "); } public static void show4(this oldclass obj, int x) { Console.WriteLine("Method four: " + x); } public static void show5(this oldclass obj) { Console.WriteLine("Method five: " + obj.a); } } } // Again add a new classTestold.cs to test the above code using System; namespace CSharpConsole { class Testold { static void Main() { oldclass obj = new oldclass(10); obj.show1(); obj.show2(); // Calling Extension Methods obj.show3(); obj.show4(50); obj.show5(); Console.ReadLine(); } } }
No comments:
Post a Comment