0

Given the following enum:

public enum SomeEnumType : byte
    {
        [Display(Name = "Name of EnumItemOne")]
        EnumItemOne = 1,

        [Display(Name = "Name of EnumItemTwo")]
        EnumItemTwo = 2,

        [Display(Name = "Name of EnumItemThree")]
        EnumItemThree = 3,

    }

I would like to use the maximal number of this enum in a data annotation (to validate the input values) using the solution from the following question: "Getting the max value of an enum"

[DisplayName("Some display name")]
[Range(1, Convert.ToInt32(Enum.GetValues(typeof(SomeEnumType)).Cast<SomeEnumType>().Max()), ErrorMessage = "Please choose an item")]
public SomeEnumType SomeField{ get; set; }

but I get the following error message:

Error CS0182 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

I do not have any idea about the root cause. Has someone faced error message like this?

  • 2
    `Convert.ToInt32(...)` is not a constant expression. Nor is any of the other stuff you're trying to cram in there. Attribute values must be computable at compile time because they must be embedded literally into the metadata -- they can't use arbitrary expressions. Specify `(int) SomeEnumType.EnumItemThree` as a literal, or use a more sophisticated `Range`-like attribute that can work with the `Type` of an enum and delegates the rest to runtime. – Jeroen Mostert Jun 13 '17 at 22:12
  • Actually, it seems they [already made that](https://msdn.microsoft.com/library/system.componentmodel.dataannotations.enumdatatypeattribute) (no personal experience with how well it works for validation purposes). – Jeroen Mostert Jun 13 '17 at 22:18
  • You can't, pure and simple. There is no compile-time expression that will give you the maximum tag value of an enum. Like I said, pass the `Type` of the enum to the attribute, then move that whole logic inside the validation method (which, apparently, `EnumDataType` already does). – Jeroen Mostert Jun 13 '17 at 22:28
  • The EnumDataType was the solution! Thank You for the answer! ;) – Tamás Varga Jun 13 '17 at 22:43

0 Answers0