sfinks_29
sfinks_29

Reputation: 918

Custom attribute: An attribute argument must be a constant expression

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?

Upvotes: 3

Views: 4021

Answers (2)

sfinks_29
sfinks_29

Reputation: 918

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.

Upvotes: 0

Backs
Backs

Reputation: 24903

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.

Upvotes: 4

Related Questions