C# Extension Methods: a Useful Example!

Total: 3 Average: 3.7

What is an extension method? The extension method provides the ability to extend the functionality of an existing class by adding a static method into this class, without creating a new derived class, recompiling, or otherwise modifying the original class. The following example demonstrates the extension method in use.

namespace NamespaceName
{
    public static class CommonUtil
    {
        public static string ListToString(this IList list)
        {
            StringBuilder result = new StringBuilder("");
            if (list.Count > 0)
            {
                result.Append(list[0].ToString());
                for (int i = 1; i < list.Count; i++)
                    result.AppendFormat(", {0}", list[i].ToString());
            }
            return result.ToString();
        }
    }
}

What does this code do? It extends all classes that implement the IList interface with the ListToString method. The ListToString method allows getting list items separated by a comma in the form of the string.

To extend the functionality of standard interface, you need to involve NamespaceName. The following example demonstrates how this method can be used.

var _list = DataContextORM.ExecuteQuery("Select name from products").ToList();
string result = _list.ListToString();

The _list variable will contain all product names. The result variable will contain a string of names separated by a comma.

Andrey Langovoy

Andrey Langovoy

Andrey Langovoy is a team leader at Devart. He takes part in development and testing database management tools for SQL Server, writes articles about SQL Server and contributes to open source projects, MSDN and MDN.