-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Instant .NET 4.5 Extension Methods How-to
By :
Now, it is time to move on to extending the string data type. There are many reasons for extending a string, from validating to manipulation. We will write two extension methods, one manipulating a string by replacing diacritic characters with non-diacritic ones and then validating it. We will also pass a parameter to the second extension to specify what kind of validation it is.
The following image shows us that Visual Studio's IntelliSense will recognize the extension method on the url string:

Refer to the StringExtensions.cs file in the ExtensionMethods.Library project for the extension methods. These methods are used in the Program.cs file in the ExtensionMethods.Console project.
The following code shows two extension methods, Validate and RemoveDiacritics:
public static bool Validate(this string value, ValidationType type)
{
switch(type)
{
case ValidationType.Email:
return Regex.IsMatch(value,
@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$");
case ValidationType.Url:
return Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute);
default:
throw new ArgumentOutOfRangeException("type");
}
}
public static string RemoveDiacritics(this string value)
{
string stFormD = value.Normalize(NormalizationForm.FormD);
StringBuilder sb = new StringBuilder();
for (int ich = 0; ich < stFormD.Length; ich++)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
if (uc != UnicodeCategory.NonSpacingMark)
{
sb.Append(stFormD[ich]);
}
}
return sb.ToString().Normalize(NormalizationForm.FormC);
}The following code shows the use of the extension methods:
var url = "http://www.mywebsite.com/articles/éxťenšíoň-meťhóďs";
//should be false due to Diacritic characters.
bool isValidUrl = url.Validate(ValidationType.Url);
//lets remove them now
url = url.RemoveDiacritics();
//should now be: http://www.mywebsite.com/articles/extension-methods
//should now be true
bool isValidUrl1 = url.Validate(ValidationType.Url);We have seen how to implement validation on strings and how to pass additional parameters to extension methods as seen in the Validate method. The way we did this is to create a method with an enum parameter to tell us the type of validation it is. The implementation of this method uses a simple switch statement to determine what validation algorithm to use, it then returns a bool value depending on how the validation went.
In the RemoveDiacritics method, we attempted to clean a string of diacritic characters, which would not pass as a valid URL. Other string cleaning methods such as HTML encoding and cleaning a string for SQL injection would be well suited as an extension method.
Some additional things to note about extension methods on strings are shown as follows:
Passing parameters: An extension method is just like a normal method and supports parameters in the same way. The second parameter in the definition is the first accepted argument when the method is called:
//the method definition public static bool Validate(this string value, ValidationType type) //calling the method bool isValidUrl = url.Validate(ValidationType.Url);
Manipulation: Strings are immutable, we will not be able to manipulate the actual string instance that the extension was called on. This is why we returned the manipulated version. In the usages snippet, we assigned the return value back to itself:
url = url.RemoveDiacritics();
In this recipe, we have created and used extension methods on the type string.
Change the font size
Change margin width
Change background colour