Say, we have a class defined in one of the assemblies shipped with a third party solution. It would be a great help if you could add a helper method to one of the objects. Unfortunately, we do not have the source code. 🙁 What do we do?
In such scenarios, .NET hasn’t left us alone in the desert 😀 The method extension technique will allow us to add our own methods to classes of our choice. Want to see an example? Take the List
Facts to remember:
— To extend a class and add method, we must declare a public static class with some name. The name doesn’t matter at all.
— We should define a method with our desired name in that class.
— The first parameter to the method will be “this < Object_we_want_to_extend > parameterName”. Do not forget the “this” keyword. It is the magic wand that does the magic.
— We can pass additional parameters.
— When calling the extended method from the original object, the first parameter is not required to pass. You can ignore it as if it were never there.
— For safety and security the extended method can not access private areas (fields, properties or methods).
So what do all these mean? Show me some codes! Okay, here you go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
using System; using System.Collections.Generic; using System.Linq; namespace Test { class Program { public static void Main(string[] args) { // Construct a list of "object" type. Setting the generic type to <object> will help us add all sorts of objects. List<object> list = new List<object>(); // Add a string, integer and hell yeah - another list of string :D list.Add("masnun"); list.Add(23); list.Add(new List<string>()); // Lets call our extended method list.Print(); // Halt the output until an enter is pressed. For a better examination of the output. Console.ReadLine(); } } //The public static class with any name you choose public static class ListExtension { // The method name is Print. We're extending a generic here, so make the method follow. public static void Print<T>(this List<T> passedList) { // We loop through the generic and print the output of ToString() foreach (T x in passedList) { Console.WriteLine(x.ToString()); } } } } |
The output shall be:
1 2 3 |
masnun 23 System.Collections.Generic.List`1[System.String] |
Cool, no? 😀 The code is commented as much as I thought necessary. Feel free to ask a question or submit any feedback you might come up with 🙂
Have fun implementing some extended methods on your own 🙂