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.

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.

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 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.
Andrey Langovoy