Book Image

Instant .NET 4.5 Extension Methods How-to

By : Shawn Ricardo Mclean
Book Image

Instant .NET 4.5 Extension Methods How-to

By: Shawn Ricardo Mclean

Overview of this book

.NET extension methods is an essential feature to know and understand for all .NET developers. Usage of extension methods is found in applications ranging from small to large scale enterprise systems built using the .NET framework. Create and use extension methods the correct way to save your development time and maintainability costs. Instant .NET 4.5 Extension Methods How-to is a practical, hands-on guide that provides you with a number of clear, step-by-step exercises that will help you take advantage of the real power that is behind extension methods and gives you good knowledge of how to use them in your .NET applications. This book covers how to create, write, and use different types of extension methods. It will take you through a number of clear, practical recipes that will help you take advantage of the power of extension methods in the quickest possible way. You will also learn exactly how to create extension methods on strings, interfaces, classes such as IQueryable and IEnumerable, and so on. You will write them from scratch and then use them practically in your application. You will also learn the most suitable scenarios for using these extension methods.You will learn everything you need to know about creating your own extension methods and using them and other external extension methods.
Table of Contents (6 chapters)

Extension methods on string data types (Must know)


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:

Getting ready

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.

How to do it...

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);

How it works...

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.

There's more…

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.