Question

Just for an example of creating a MD5 hash, microsoft provided this code sample:

MSDN Code

// in Helpers class
public static string GetMd5Hash(MD5 md5Hash, string input)
{
    byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
    StringBuilder sBuilder = new StringBuilder(); 
    for (int i = 0; i < data.Length; i++)
    {
        sBuilder.Append(data[i].ToString("x2"));
    }
    return sBuilder.ToString();
}

and using it would be done like this

public string CreateHash(string str)
{
    using (var md5Hash = MD5.Create())
    {
        return Helpers.GetMd5Hash(md5Hash, str);
    }
}

My Code

I thought changing the code Microsoft provided to this, would make it easier regarding reusability of the helper method:

// in Helpers class
public static string GetMd5Hash(string input)
{
    using (var md5Hash = MD5.Create())
    {
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
        StringBuilder sBuilder = new StringBuilder(); 
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }
}

So reusing it creates less code lines as a result:

public string CreateHash(string str)
{
    return Helpers.GetMd5Hash(str);
}

So what is the purpose of not doing it like I did in my second example? My initial thought was, that programmers, who use the code MSDN provided, would always be aware of the fact, that they use unmanaged resources (is this the right term?), whereas they wouldn't if they used my implementation.

Any other thoughts?

Was it helpful?

Solution

This sample from msdn is abit more generic, as there are different overloads of Create on the MD5 class, allowing to use different hashing algorithms.

Notice how they use it: whoever uses this function can provide any instance of the MD5 class, and it will work. Of course, as I said in my comment, their samples are usually far from being perfect and I dont think too much though's been put in it

OTHER TIPS

The MSDN code would be more efficient if you wanted to reuse the md5Hash in the scope of CreateHash

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top