This is very useful if your trying to:
- Extend a class/type for which you don't hold the source
- Extend a class/type without the need to create a derived type
- Extend a sealed class/type
Here is a small example:
Ever tried to call the .ToString() method on an object that is null?
Guess what happens?
Yes. You get an exception! Your program explodes! GHAAAA!
Who to fix this?
Test if object is anything else but null. But you have to do this in every peace of code you want to convert type to string.
You could do a method that takes an argument and returns a string.
But there are cleaner/smarter ways to do this.
This is where extension methods kicks in.
Take a look at this class.
/// <summary> /// object Extention methods /// </summary> public static class ObjectExtensions { /// <summary> /// Extends the ToString Method for object types. Adds null objects support. /// </summary> /// <param name="obj">The object variable</param> /// <returns>String conversion of the object. Supports null objects</returns> public static string ToStringEx(this object obj) { return (obj == null) ? string.Empty : obj.ToString(); } }
The static method inside this also static class takes an argument that is the object it self (that's why the this word is before the argument).
What this actually does is to extend the object type. object type is the origin point of all classes in C# so everything derives from object.
By extending the object type like in the code above you will be able to call .ToString() or .ToStringEx() on every type.
For example lets say you have a class named Foo and you declare an object of that type.
Foo a; a.ToStringEx(); // Will return an empty string a.ToString(); // Will throw an exception because a is not an instance of an object
If your extension needs some input arguments it's as simple as:
public static returntype MyMethod(this targettype obj, type arg1, type arg2, ...)
There are some limitations
- Your extensions can only come in the form of methods (forget about extending properties, events, etc...)
- Your extension can only create new objects inside it's scope. No new object inside the class are allowed. For that you must inherit/derive a new class
For more info check out MSDN
No comments:
Post a Comment