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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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.
1 2 |
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
Latest posts by Andrey Langovoy (see all)
- Everything you should know about SQL Server JOINS - March 13, 2017
- Creating and Accessing In-Memory OLTP Databases and Tables - January 16, 2017
- SQL Server In-Memory OLTP: The Basics - September 9, 2016