C# Enum error : is a 'type', which is not valid in the given context

22,941

Solution 1

Instead of UtilConstants.BooleanValues (which indeed is a type and not a value), you need to use actual values. Like this:

UtilConstants.BooleanValues.TRUE | UtilConstants.BooleanValues.FALSE

Or if you actually want to check if an input string matches a constant of an enum type, you should change the signature:

public static bool isAnOptionalValidValue(Status status, String parameterName,
                                          Object parameter, Type enumType)

That way your proposed method call using typeof would work.
You could then get the actual String values of your enum by calling Enum.GetValues(enumType)

Solution 2

Enum setOfValues in the parameter list means that you passing specific value like BooleanValues.TRUE - not type itself. To pass type use Type setOfValues.

To parse specific enum value from string use

BooleanValues enumValue = (BooleanValues)Enum.Parse(typeof(UtilConstants.BooleanValues), stringValue);
Share:
22,941
pablof
Author by

pablof

Updated on August 08, 2022

Comments

  • pablof
    pablof almost 2 years

    I have a code in C# (.NET 2.0), where I call a method with an input Enum, but I cannot manage to make it work.

    I have a compile error in the method isAnOptionalBooleanValue:

    public static bool isAnOptionalBooleanValue(Status status, String parameterName, Object parameter) 
    {
        return isAnOptionalValidValue(status, parameterName, parameter, UtilConstants.BooleanValues);
    }
    
    public static bool isAnOptionalValidValue(Status status, String parameterName, Object parameter, Enum setOfValues)
    {
         ....
    }
    

    In other class:

    public class UtilConstants
    {
        public enum BooleanValues
        {
            TRUE, FALSE
        }
    }
    

    This class exists because the boolean value comes as an input String from other system, so I pass it as an Object and translate it to a Boolean from my Enum class.

    The error it returns is the following: "UtilConstants.BooleanValues' is a 'type', which is not valid in the given context" with the error in the return isAnOptionalValidValue(...) line.

    But I don't see how to fix it. Changing it by:

    return isAnOptionalValidValue(status, parameterName, parameter, typeof(UtilConstants.BooleanValues));

    does not work either.

    Any ideas? Thank you for your help in advance!