C# 3.0 - Extension methods
Helper classes grown up
by Ravi Bhavnani, 11 Feb 2008
|
Home
All articles
|
Like most developers, over the years I've gathered a collection of
handy helper classes that provide useful operations for strings,
UI controls and general parsing. C# 3.0's extension methods
allow these helper classes to be used in a much more direct and
intuitive way.
I recently began a .NET rewrite of
TakeStock,
my popular freeware personal financial management application written in
MFC. The MFC version contained a string helper class that was easily
ported to .NET. The class has an assortment of methods to validate
and parse strings representing numeric data and stock symbols; something
along the lines of:
1 // A collection of handy-dandy operations on strings.
2 public static class StringHelper
3 {
4 // Check if the string represents an integer.
5 public static bool IsInteger
6 (string s)
7 {
8 int intValue = 0;
9 if ((s != null) && Int32.TryParse (s, out intValue))
10 return true;
11 return false;
12 }
13
14 // Get the string's integer value.
15 public static int GetIntValue
16 (string s)
17 {
18 int intValue = 0;
19 if ((s == null) || !Int32.TryParse (s, out intValue))
20 throw new InvalidOperationException();
21 return intValue;
22 }
23 }
The addition of the this keyword before the "string s"
parameter converts each helper method into an extension method - i.e. one
that extends the behavior of string class.
1 // Check if string represents an integer.
2 public static bool IsInteger
3 (this String s)
4 {
5 ...
6 }
7
8 // Get the string's integer value.
9 public static int GetIntValue
10 (this String s)
11 {
12 ...
13 }
Now, by simply adding a "using StringHelper;" directive to my
code, I can use these helper methods as though they're part of .NET's
string class.
1 using StringHelper;
2 ...
3 string someString = "...";
4 int someIntValue;
5 if (someString.IsInteger())
6 someIntValue = someString.GetIntValue();
Extension methods can also take arguments. This example defines an
extension method that tests whether the string represents an integer
larger than a minimum value.
1 // Check if the string represents an integer
2 // more than a specific minimum value.
3 public static bool IsIntegerMoreThan
4 (this string s,
5 int minValue)
6 {
7 int intValue = 0;
8 if ((s != null) &&
9 Int32.TryParse (s, out intValue) &&
10 (intValue > minValue))
11 return true;
12 return false;
13 }
As before, we use this extension method as if it was part of the string class.
1 string someString = "...";
2 if (someString.IsIntegerMoreThan (42))
3 ...;
Visual Studio's Intellisense even identifies IsIntegerMoreThan as an
extension method, making it easy to use.
And there you have it. Extension methods - a welcome extension to the C# language.
|