Monday

Code - Extension Methods in C#

Extension methods are used to inject methods into existing types without having to extend the types by creating new inherited classes, recompiling or modifying the original type. Extension methods are a special kind of static method which get associated with a type as if they are the instance method of a type.

For example, you may like to know whether a certain string is a web URL or not. The general approach would be to either create a method in a utility class or extend the String type by sub-classing it and create a method in there for this operation. By following this approach one will end-up either creating tons of methods in a utility class or creating bunch of derived classes.

To address this common problem .NET has a simple yet elegant solution, and that is “Extension Methods”.To create an extension method for a type, all you have to do is to create a static class and start adding methods into it as shown below:

using System;
using System.Text;
using System.Windows.Forms;

namespace ExtensionMethods
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnRunExtensionMethods_Click(object sender, EventArgs e)
        {
            string webUrl = "http://blog.osamamirza.com";
            bool result = webUrl.IsWebUrl();

            string result2 = "Extension ".ConcatStrings("methods ","are ", "amazing");
        }
    }

    public static class ExtensionMethods
    {
        public static bool IsWebUrl(this string s)
        {
            return Uri.IsWellFormedUriString(s, UriKind.RelativeOrAbsolute);
        }


        public static string ConcatStrings(this string s, params string [] chunks)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(s);
            for (int i = 0; i < chunks.Length; i++)
            {
                sb.Append(chunks[i]);
            }
            return sb.ToString();
        }
    }
}
As you can see that extension methods are so easy to work with. Even when you are trying to use an extension method in visual studio, the IDE will also distinguish between an extension method and a built-in method by putting a little different icon infront of the extension method so that you don't get confused while working with complex APIs.


No comments:

Post a Comment

Your comments are highly appreciated!