Have you ever wanted to be able to extend a sealed class like string? With Visual Studio 2008 and C# 3.0, you now can with Extension Methods. You create these new methods to add additional custom abilities to an existing type, even if you don't have access to it. These new methods need to be static methods contained in static classes, and the first parameter should be the keyword this and the hosting type. This is demonstrated in the example below on line 8. This example takes input from the console and validates it against a regex string.
1: using System;
2: using System.Text.RegularExpressions;
3:
4: namespace ExtensionMethods
5: {
6: public static class MyClass
7: {
8: public static bool ValidPhoneNumber(this string s)
9: {
10: string valid_phone = "^[\\(]{0,1}([0-9]){3}[\\)]{0,1}[ ]?([^0-1]){1}([0-9])" +
11: "{2}[ ]?[-]?[ ]?([0-9]){4}[ ]*((x){0,1}([0-9]){1,5}){0,1}$";
12:
13: Regex regex = new Regex(@valid_phone);
14: return regex.IsMatch(s);
15: }
16: }
17:
18: class Program
19: {
20: static void Main(string[] args)
21: {
22: Console.Write("Please Enter Phone Number: ");
23: string newPhone = Console.ReadLine();
24:
25: if (newPhone.ValidPhoneNumber())
26: Console.WriteLine("Good Phone Number");
27: else
28: Console.WriteLine("Bad Phone Number");
29:
30: Console.ReadLine();
31: }
32: }
33: }
Once the class has been created, it can be used as an extension of the string class as simply as if it was originally part of the it.
Other examples can be found at the blogs for David Hayden, or Scott Guthrie.
Remember Me
Page rendered at Wednesday, December 03, 2008 10:02:07 PM (Eastern Standard Time, UTC-05:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.