As a mobile developer for .Net solutions, I often encounter the need to validate the mobile number of a subscriber if it conforms to the correct format. More often, I always create a utility class to do the validation.
One thing I learned from using the latest .NET 3.5 Framework is Extension Method.
So, the way I enable my program to use extension method is as follows:
Method 1:
via the old way:
1: using System.Text.RegularExpressions;
2:
3: namespace MyConsoleTester
4: {
5: class Utils
6: {
7: public static bool IsValidMobile(string number)
8: {
9: bool bFound = false;
10: try
11: {
12: bFound = Regex.IsMatch(number, @"\A\+\b(639)[012]{1}[0-9]{1}[0-9]{3}[0-9]{4}\b\Z");
13: }
14: catch (ArgumentException)
15: {
16:
17: }
18:
19: return bFound;
20: }
21: }
22: }
and the implementation would be:
1: string number = "+639303782321";
2: bool numValid = Utils.IsValidMobile(number);
3: Console.WriteLine("Is {0} valid? {1}", number, numValid);
Method 2:
via extension method offers much better and cleaner:
1: using System.Text.RegularExpressions;
2:
3: namespace MyConsoleTester
4: {
5: public static class SampleExtensions
6: {
7: public static bool IsValidMobile(this string number)
8: {
9: bool bFound = false;
10: try
11: {
12: bFound = Regex.IsMatch(number, @"\A\+\b(639)[012]{1}[0-9]{1}[0-9]{3}[0-9]{4}\b\Z");
13: }
14: catch (ArgumentException)
15: {
16:
17: }
18:
19: return bFound;
20: }
21: }
22: }
and the implementation would be as beautiful as this:
1: using MyConsoleTester;
2:
3: Console.WriteLine("Valid Mobile: +639203782321:\t{0}", "+639303782321".IsValidMobile());
This extension method also posted in ExtensionMethod.net