Is it possible for me to declare a variable, without a type, then specify the type based on some conditions? For example, I want to create a SHA Hash object based what size the user would like to use:
//get the Sha hasher
var shaHash;
switch (this.HASH_ALGORITHM)
{
case HashAlgorithm.SHA256: //HashAlgorithm is an enum.
shaHash = SHA256.Create();
break;
case HashAlgorithm.SHA384:
shaHash = SHA384.Create();
break;
case HashAlgorithm.SHA512:
shaHash = SHA512.Create();
break;
}
//... do hashing
Is this possible?
No, that won't work. But, given that all three of those types inherit from System.Security.Cryptography.HashAlgorithm
, you could declare the variable of that type:
HashAlgorithm shaHash;
switch(this.HASH_ALGORITHM)
{
// snip
}
Edit
Just to add, the reason that var shaHash;
will not work is because that var
is just a shorthand way of saying "I'm not sure of the best type to use here, so please infer it for me". The compiler requires that you specify an initial value so that it can determine the best type to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With