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)

Overloading extension methods (Should know)


Most OOP languages allow us to have methods with the same name but different parameters, which is known as function overloading. Overloading extension methods is the same as function overloading and follows the same criteria. In this recipe, you will learn function overloading as it relates to extension methods.

The following screenshot shows that Visual Studio's IntelliSense will list all the overloaded extensions on the user object:

Getting ready

Refer to the UserExtensions.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; CreateSalt and SetHashedPassword:

/// <summary>
/// Creates a random string of a specific size.
/// </summary>
/// <param name="size"></param>
/// <returns></returns>
private static string CreateSalt(int size)
{
    var rng = new RNGCryptoServiceProvider();
    var buff = new byte[size];
    rng.GetBytes(buff);
    return Convert.ToBase64String(buff);
}

/// <summary>
/// Hash a string using SHA256Managed Algorithm
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Hash(string value)
{
    HashAlgorithm algorithm = new SHA256Managed();
    Byte[] inputBytes = Encoding.UTF8.GetBytes(value);

    Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
    return BitConverter.ToString(hashedBytes);
}

/// <summary>
/// Hashes and set a password with a generated salt.
/// </summary>
/// <param name="value"></param>
/// <param name="password"></param>
/// <returns></returns>
public static User SetHashedPassword(this User value, string password)
{
    string generatedSalt = CreateSalt(25);

    return SetHashedPassword(value, password, generatedSalt);
}

/// <summary>
/// Hashes and set a password with the salt argument.
/// </summary>
/// <param name="value"></param>
/// <param name="password"></param>
/// <param name="salt"></param>
/// <returns></returns>
public static User SetHashedPassword(this User value, string password, string salt)
{
    value.Password = Hash(string.Concat(password, salt));
    value.PasswordSalt = salt;
    return value;
} 

The following code shows the use of the extension methods:

User user = new User();
user.SetHashedPassword("samplepassword");

User user1 = new User();
user1.SetHashedPassword("samplepassword", "myownsalt");

How it works...

In the code snippets, we have added two extension methods (SetHashedPassword) for hashing and setting a password.

The first method only takes a password parameter, generates a salt by calling another static method, then passes the password and salt to the second extension method that will handle the hashing and modification of the properties. You may have noticed that we called the second extension method as a normal static method:

return SetHashedPassword(value, password, generatedSalt);

Here are some additional information to consider when overloading extension methods:

  • Criteria for overloading: The compiler will verify that a method is overloaded based on the argument type or the number of arguments and that they have the same name. The return type is not considered in the function signature.

  • Calling an overloaded extension: The decision of which method is called is made at compile time, based on the parameters that you used when calling it. Visual Studio's IntelliSense will also give you an idea of what overloads are available to you.

Try to limit the number of overloaded methods, as this causes confusion to the developer using these methods.

In this recipe, you have learned how to create and use overloaded extension methods.