3

I have defined a custom enum DescriptionAttribute (see my previous question: Multiple enum descriptions)

public class DescriptionWithValueAttribute : DescriptionAttribute
{
    public Decimal Value { get; private set; }

    public DescriptionWithValueAttribute(String description, Decimal value)
        : base(description)
    {
        Value = value;
    }
}

My enum looks like this:

public enum DeviceType
{
    [DescriptionWithValueAttribute("Set Top Box", 9.95m)]
    Stb = 1,
}

I get the following error when compiling:

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

I have also tried: [DescriptionWithValueAttribute("Set Top Box", (Decimal)9.95)]

Any ideas?

Community
  • 1
  • 1
sfinks_29
  • 876
  • 4
  • 20
  • 30
  • 1
    Decimals can't be used as attribute parameters. See http://stackoverflow.com/questions/507528/use-decimal-values-as-attribute-params-in-c – BoltClock Oct 08 '15 at 05:23

2 Answers2

4

According to this article:

Attribute parameters are restricted to constant values of the following types:

  • Simple types (bool, byte, char, short, int, long, float, and double)
  • string
  • System.Type
  • enums object (The argument to an attribute parameter of type object must be a constant value of one of the above types.)
  • One-dimensional arrays of any of the above types

So, you cant use Decimal. Replace it with float or double. Other way - store value as string and parse it.

Backs
  • 24,430
  • 5
  • 58
  • 85
0

I have updated my custom enum DescriptionAttribute to the following:

public class DescriptionWithValueAttribute : DescriptionAttribute
{
    public Decimal Value { get; private set; }

    public DescriptionWithValueAttribute(String description, Double value)
        : base(description)
    {
        Value = Convert.ToDecimal(value);
    }
}

It expects a Double then converts to Decimal, as I need the final value as a Decimal. Works as expected.

sfinks_29
  • 876
  • 4
  • 20
  • 30