What are extension methods? This is an opportunity to expand the functionality of an existing class by adding a static method to it. Here is a simple example that at the same time remains very useful to me.
namespace SampleNS
{
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, which allows you to get a comma-separated list of list elements as a string. To extend the functionality of the standard interface, all that is needed now is to connect the SampleNS namespace. (Comment: thanks to the very useful remark of
easyman , the example was rewritten using the StringBuilder class)
Here is an example of use:
var _list = DataContextORM.ExecuteQuery <string> ("Select name from products"). ToList ();
string result = _list.ListToString ();
This example will receive in _list a list of names of all products, and then assign a string with a comma-separated list of names to the result variable.
PS: transferred from a personal blog