Extension methods were introduced to .NET in C# 3.0. They provide an effective way to extend existing types and provide an intuitive way to add functionality to classes that you may not otherwise have the ability to modify. One simple example for which I use an extension method is to display booleans in the UI. Consider an online shop listing products, where you want to tell the user whether the item is "In Stock". If you bind the boolean directly, the user will see "True" or "False" in the UI. While this may get the point across to the user, it is far from user-friendly. You should indicate "Yes" or "No", rather than true/false. There are certainly several ways to accomplish this easily, but I find an extension method intuitive to code against and re-usable.
To accomplish this:
1) Create a static class that will house your extension methods.
2) Add the method below to that class.
3) Reference the dll and namespace of your extension method class.
4) Write client code to use it, for example, product.IsInStock.ToYesNo().
public static string ToYesNo(this bool value)
{
if (value) return "Yes";
return "No";
}
This is a simple, practical usage of extension methods and how to utilize them.