C# Extension Methods

Extension methods are a very useful tool to add methods to an existing type without having to create your own custom type. You create them in a static class by creating a static method that takes an argument of the object type you want to extend, the argument is preceded by the this modifier.

Here are some example String Extensions


namespace Extensions
{
    public static class StringExtensions
    {
        public static bool IsNullOrEmpty(this string value)
        {
            return string.IsNullOrEmpty(value);
        }

        public static string Left(this string s, int count)
        {
            return s.Substring(0, count);
        }

        public static string Right(this string s, int count)
        {
            return s.Substring(s.Length - count, count);
        }

        public static string Mid(this string s, int index, int count)
        {
            return s.Substring(index, count);
        }

        public static int ToInteger(this string s)
        {
            int integerValue = 0;
            int.TryParse(s, out integerValue);
            return integerValue;
        }

        public static bool IsInteger(this string s)
        {
            Regex regularExpression = new Regex("^-[0-9]+$|^[0-9]+$");
            return regularExpression.Match(s).Success;
        }
    }
}

The above extension would let you do this


            string Name = "John";

            Name.IsNullOrEmpty();
            Name.IsInteger();
            Name.IsNull();

Here is an example extension that extends the HttpResponse and HttpRequest objects


namespace Extensions
{
    public static class HttpExtensions
    {
        public static void Redirect301(this HttpResponse response, string url)
        {
            response.AddHeader("Location", url);
            response.Status = "301 Moved Permanently";
            response.StatusCode = 301;
            response.Flush();
            response.End();
        }

        public static string GetString(this HttpRequest httpRequest, string key)
        {
            if (!String.IsNullOrEmpty(httpRequest.QueryString[key]))
                return (string)httpRequest.QueryString[key];

            return string.Empty;   
        }

        public static int GetInt(this HttpRequest httpRequest, string key)
        {
            if (!String.IsNullOrEmpty(httpRequest.QueryString[key]))
                return int.Parse(httpRequest.QueryString[key]);

            return -1;
        }
    }
}

The above extension would let you do this


            int productId = Request.GetInt("ProductId");
            string category = Request.GetString("Category");

            Response.Redirect301("~/Default.aspx");

Or how about these that extend an Object


namespace Extensions
{
    public static class ObjectExtensions
    {
        public static bool IsNull(this object value)
        {
            return (value == null);
        }

        public static bool IsNullOrEmpty(this object obj)
        {
            if (obj == null)
                return true;

            if (string.IsNullOrEmpty(obj.ToString()))
                return true;

            return false;
        }
    }
}

The above code would allow


            Object person = new Object();

            person.IsNullOrEmpty();
            person.IsNull();

Here are a few Xml Extensions:


using System.Xml.Linq;

public static class XmlExtensions
{
  public static T Deserialize< T >(this XElement xml)
  {
    return Serializer.Deserialize< T >(xml.ToString());
  }

  public static string Serialize< T >(this T obj)
  {
    return Serializer.Serialize(obj);
  }

  public static XElement ToXElement(this string xml)
  {
    return XElement.Parse(xml);
  }
}



Comments

  1. Jonathan Danylko February 2nd

    Comment Arrow

    I love them as well.

    I wrote a post about -my- favorite extension methods.

    http://www.danylkoweb.com/Blog/10-extremely-useful-net-extension-methods-8J

    Just wanted to share. 🙂


Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.