Extension Methods in C#

Just a little braindump for later use. Extension methods allow you to add ‘new methods’ to an existing class without changing the internal behavior of the original class. This can be done even on sealed classes or interfaces. You can not ‘override’ or hide an existing method. In case you try to hide a method, the compiler will automatically choose the original method, ignoring your implementation. An extension method is a public static method in a public static class. The first parameter specifies which type the method operates on, and is preceded by the this modifier.

In the example below we extend type string with a ToInt32 method (normally found in Convert). If the input string can’t be converted to an int, we throw an exception.

using System;

namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            string i = "100";
            string s = "Hello World";

            try
            {
                // add up 100
                Console.WriteLine(i.ToInt32() + 100);

                // force an exception
                Console.WriteLine(s.ToInt32());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();
        }
    }

    public static class StringExtensionMethods
    {
        public static Int32 ToInt32(this string s)
        {
            int result;
            bool isNumber = Int32.TryParse(s, out result);

            if (!isNumber)
            {
                throw new FormatException(
                    string.Format("{0} is not a valid integer", s));
            }

            return result;
        }
    }
}

You’ll find a large number of shared Extension Methods here.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>