I thought that a great way to test my understanding of common functions would be to create a function that spits out the hexadecimal representation of the hash using one of the classes that inherits from HashAlgorithm. Since all HashAlgorithm classes offer ComputeHash, I thought it would be simple. When I build such a function. although, I get an error because HashAlgorithm itself does not offer a constructor. I could not find any interface or subclass of HashAlgorithm that the constructor also offers. If not all HashAlgorithm classes are needed to support the constructor, is there some additional restriction that I can impose on the generic type to ensure that the type offers an empty constructor, or I will be forced to create an overload for each of the HashAlgorithm classes,which I know an empty constructor.
Here is what I still have (in a 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();
}
Change Answer Hamilton Matt immediately nailed it, just complicating common limitation: where HashAlgorithmToUse : HashAlgorith, new()
. I did not even understand that I could have several limitations. I definitely have a way before I fully understand everything I can do with Generics. I believe that you can make a very non-general, general function if you are too keen on restrictions.
source
share