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:
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
// Lets call our extended method
// Halt the output until an enter is pressed. For a better examination of the output.
//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)
The output shall be:
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 🙂