18 July, 2012

Extension Methods

Extension methods were introduced with C# 3.0 and allow the developer to extend an existing type with new functionality without modifying the original type. Extension methods are implemented as static methods that reference the target type by using the ‘this’ keyword. Visual Studio automatically provides intellisense support and compile time checking for all extension methods.

The following example adds an extension method to the string type that determines if the length of a sting is equal to or larger than a given length:
namespace ExtensionMethods
{
    public static class ExtensionMethods
    {
        public static bool HasMinLength(this string s, int minLength)
        {
            return s == null ? false : s.Length >= minLength;
        }
    }
}
To use the extension method the namespace of the extension method must either be imported or part of a parent namespace of the current class:
using ExtensionMethods;

namespace MyProgram
{
    class Program
    {
        public static void Main(string[] args)
        {
            var s = "MyString";
            
            if(s.HasMinLength(5))
                Console.WriteLine("Length is not to short");
            else
                Console.WriteLine("Length is to short");
        }
    }
}
Extension methods support inheritance of classes which means that an extension method for a parent type is also available to inherited types. By creating an extension method for the object type the extension method is available to all types since the object type is the base class of every type:
public static bool IsOfType(this object o, Type t)
{
    return o.GetType() == t;
}
This method can now be used on all objects to determine if an object is of a particular type:
var s = "MyString";
var i = 11;

s.IsOfType(typeof(string));  // Returns true
i.IsOfType(typeof(double));  // Returns false
There are no security risks by using extension methods since extension methods cannot be used to override instance methods and the extension method is not able to access any private variables of the class. This means that if an extension method contains the same name and signature as an instance method, the instance method will always be called during execution.

No comments:

Post a Comment