Written by 10:39 Basics of C#, Languages & Coding

C# Extension Methods: a Useful Example!

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.

Tags: Last modified: September 23, 2021
Close