Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable of unspecified type in C#?

Tags:

c#

types

sha

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?

like image 521
Petey B Avatar asked Nov 29 '22 10:11

Petey B


1 Answers

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.

like image 87
mdm Avatar answered Dec 16 '22 19:12

mdm