I have three enums:
enum ValueType : int
{
FloatingPoint = 2,
.../...
}
enum ConstraintType : int
{
Range = 2,
.../...
}
enum Parameter : int
{
ExposureTime = F(ValueType.FloatingPoint, ConstraintType.Range, 23),
.../...
}
The problem is in the signature of F
if I use:
private static int F(ValueType _V, ConstraintType _C, int _N) { ... }
I get an error (invalid arguments) for every call in the definition of Parameter
, but if I use the following instead:
private static int F(int _V, int _C, int _N) { ... }
Everything is fine.
It's not a blocking problem, but I'd like to understand why is that.
Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
By default enums have their own string values, we can also assign some custom values to enums.
With the help of enum. auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Automatically assign the integer value to the values of enum class attributes.
The valueOf() method returns the value of given constant enum.
The C# spec states in section 14.3 ("Enum members") that
Within an enum member initializer, values of other enum members are always treated as having the type of their underlying type, so that casts are not necessary when referring to other enum members.
As far as I can tell this is why the arguments appear to have a type of int
. It's interesting to note that this will not result in an invalid argument error:
ExposureTime = F((ValueType)ValueType.FloatingPoint,
(CostraintType)ConstraintType.Range,
23),
Of course it will still result in another error because you cannot use a method call to initialize enum members as Marc says. A method call is not a constant expression, while
The associated value of an enum member is assigned either implicitly or explicitly. If the declaration of the enum member has a constant-expression initializer, the value of that constant expression, implicitly converted to the underlying type of the enum, is the associated value of the enum member. If the declaration of the enum member has no initializer, its associated value is set implicitly [...]
For enums with explicit values, the value must be a constant expression. F(...)
is not a constant expression. Regardless of whether the parameters are int
or enums, you cannot assign an enum value from a function call.
Your "everything is fine" actually means:
The expression being assigned to 'blah.Parameter.ExposureTime' must be constant
The only "problem" here is that the compiler doesn't give a very elegant error message to a particular illegal scenario.
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