Listing 1 - Extension Method Sample
namespace MyExtensions { public static class DebugExtensions { public static void Print(this object anObject, string message) { Console.WriteLine(String.Format("{0} {1}", message, anObject)); } } } |
The this keyword in front of the object type in the Print method marks the Print method as an extension method. Because the Print method defines a parameter this object, the Print method can extend every class that inherits from the object type! To some this may seem a bit dangerous, but it does provide a way to print debug info on every possible class that include the using MyExtensions in the class file. For Example you can use Print method extension on an integer as well as a string as shown in listing 2:
Listing 2 - Implementing the Extension Method
using MyExtensions;
int x = 54; x.Print( "The number is");
string msg = "Go to C# Corner"; msg.Print("The Message is"); |
Extending the string class
Although the object extension is perhaps a bit type unsafe, you can extend a specific class called myclass just by using this myclass. Below we extended the string class with this string. This way only the string class can use the extended methods. Any other class trying to use the string extension methods will throw a compilation error. We've provided five string extensions in our example. With a little thinking, I'm sure one can think of many more possibilities. The methods are defined in the table below (you may recognize some of them from the early VB days).
Table 1 - String Method Extensions
String Extension Method |
Description |
string Left (int count) |
Gets the first count characters of the string |
string Right(int count) |
Gets the last count characters of a string |
string Mid(int index, int count) |
Gets count characters starting at index |
bool IsInteger |
Determines if the string is an integer |
ToInteger |
Converts the string to an integer |
Note that most of these methods are trivial and can easily be realized via other classes in the .net framework. They just provide a good example of how you can extend the framework to suit your needs. Listing 2 shows the implementation of the string extension methods listed in table 1:
Listing 3 - Some String Extensions for the System.String class