Jaggu
Jaggu

Reputation: 6428

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

I want to pass some list of enums to my Attribute property. But it's pretty you can pass List to Attribute's property. So I tried converting it to string representation and tried to do something like this:

[MyAtt(Someproperty = 
            Enums.SecurityRight.A.ToString() + "&" + (Enums.SecurityRight.B.ToString() ))]

However, this gives the error: "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"

I understand you can only pass constants. But how do I get away with this? Any tricks?

Thanks.

Upvotes: 4

Views: 13014

Answers (1)

Hand-E-Food
Hand-E-Food

Reputation: 12794

Please pardon me if my C# coding is off. I use VB.

You can use const values.

namespace Enums {
    static class SecurityRight {
        const String A = "A";
        const String B = "B";
    }
}

[MyAtt(StringProperty = Enums.SecurityRight.A + "&" + Enums.SecurityRight.B)]

You can use an enum if the attribute accepts the same data type as an enum.

namespace Enums {
    [Flags()]
    enum int SecurityRight {
        A = 1;
        B = 2;
    }
}

[MyAtt(IntegerProperty = Enums.SecurityRight.A | Enums.SecurityRight.B)]

EDIT: Changed IntegerProperty above to receive multiple values.

Attributes are set at compile time, not at runtime. By using ToString, you are invoking code that is used in runtime. You must use a constant value.

Upvotes: 7

Related Questions