The following is an extension method
Listing 1
namespace Nucleo.Primitives
{
public static class StringExtensions
{
public static bool IsMatch(this string value, string regularExpression)
{
return Regex.IsMatch(value, regularExpression);
}
}
}
Let's look at it in detail. First, note the usage of the
"this" keyword; whatever type that is designated for the property
with the "this" keyword is the type that will be extended. So, in
this example, this method is added to the string class. This means that you
could do:
Listing 2
string value = "4545";
Assert.IsTrue(value.IsMatch(@"\d+"));
And this will work. When you call IsMatch, it invokes our
static StringExtensions IsMatch method. This is a requirement; both the class
and method have to be defined as static. Secondly, the first parameter must be
defined with the "this" keyword. Note one thing; the first parameter
defines the type to extend, but the rest of the parameters are the parameters
of the instance method on the class.
What I mean by that is IsMatch has one string parameter:
regularExpression. If the method were defined as
Listing 3
public static bool IsMatch(this string value, string regularExpression,
RegexOptions options)
{
}
You would invoke it as
Listing 4
Assert.IsTrue(value.IsMatch(@"\d+", RegexOptions.None));
So, for every parameter after the "this"
parameter, these are the parameters of the method. Also note that you can use
whatever return type you want (void, bool, string) as it's the return type of
the method, and you can also define whatever scope you want, though the most
beneficial is public scope.
One thing to note: our static extension is defined in the
Nucleo.Primitives namespace; this means that you have to define the following
using statement for the extension method to even appear
Listing 5
Otherwise, the extension method will not appear for any
string instances.