For those wondering what extension methods are: they are an easy portable way to extend functionality of a class that you are using. I have used them to extend HtmlHelper in .Net MVC (See the post where I create a submit button using these Extension Methods on HtmlHelper), I have also used them to automate some of the overhead of using the Microsoft AJAX ControlToolkit with MVC. Past that, there are many other "Code Practices" that could make knowing these very easy. I was just toying with (for practice) creating extension methods because I really want to understand this in full. This is a small example of it in a Console application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringExtensionDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input "
+"String to print backwards: ");
var demo = Console.ReadLine();
// Regular string calling the extension method (Below)
Console.WriteLine(demo.Reverse());
Console.ReadLine();
}
}
public static class StringExtension
{
public static string Reverse(this string str)
{ //Just reverse the string however you want.
var Holder = "";
for (int i = str.Length - 1; i >= 0; i--)
{
Holder += str[i];
}
return Holder;
}
}
}
The first method is the main() method. This just simply does things using the console window. The second is the custom Reverse() method that I call to reverse the string. As you can see, this is a really powerful feature and much easier to implement here than any other languages I have seen. There were lots of warnings around the web that indicate that you should be very careful not to over do this when using these Extension methods in CSharp. Here is a picture for anyone that is wondering how this should work.