tags:

views:

357

answers:

2

I thought a great way to test my understanding of generic functions would be to create a function that would spit out a hex representation of a hash using one of the classes that inherits from HashAlgorithm. Since all of the HashAlgorithm classes offer ComputeHash, I thought this would be simple. When I construct such a function. though, I get an error because HashAlgorithm itself doesn't offer a constructor. I couldn't find any sort of interface or subclass of HashAlgorithm that does offer a constructor, either. If not all HashAlgorithm classes are required to support a constructor, is there some additional constraint I can put on a generic type to ensure a type offers an empty constructor or will I be forced to create an overload for each of the HashAlgorithm classes I know offer an empty constructor.

Here is what I have so far (in its non-compiling state):

public static string GetHexHash<HashAlgorithmToUse>(Stream dataStreamToHash) where HashAlgorithmToUse : HashAlgorithm
{
 StringBuilder Result = new StringBuilder();
 byte[] ByteHash = (new HashAlgorithmToUse()).ComputeHash(dataStreamToHash);
 foreach (byte HashByte in ByteHash)
 {
  Result.Append(HashByte.ToString("X2"));
 }
 return Result.ToString();
}

Edit Matt Hamilton's answer nailed it right away, simply making the generic constraint more complex: where HashAlgorithmToUse : HashAlgorith, new(). I didn't even realize I could have multiple constraints. I definitely have a way to go before I fully understand all I can do with Generics. I suppose you can make a very non-generic, generic function if you get too carried away with the constraints.

+2  A: 

Try adding the new() clause to the end of your generic constraints:

public static string GetHexHash<HashAlgorithmToUse>(Stream dataStreamToHash)
    where HashAlgorithmToUse : HashAlgorithm, new()

This tells the type that "HashAlgorithmToUse" has a parameterless (default) constructor. Should do the trick.

Matt Hamilton
Beat me by a minute.
recursive
A: 

At least in Visual Studio 2008, adding the new() constraint to the function got it to compile for me:

public static string GetHexHash<HashAlgorithmToUse>(Stream dataStreamToHash) where HashAlgorithmToUse : HashAlgorithm, new()
{
    // ...
}
Andy