4

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.

Jaggu
  • 6,298
  • 16
  • 58
  • 96
  • 1
    duplicate of http://stackoverflow.com/questions/270187/can-i-initialize-a-c-attribute-with-an-array-or-other-variable-number-of-argumen – Adam Ralph Oct 12 '11 at 05:16

1 Answers1

7

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.

Hand-E-Food
  • 12,368
  • 8
  • 45
  • 80
  • Nice but not exactly what I was looking for. I was looking for your 2nd approach where enum is used. I want to send in 2 enum in 1 property. But you only sent one. [MyAtt(IntegerProperty = Enums.SecurityRight.A)] – Jaggu Oct 12 '11 at 05:25
  • how does this allow passing of a list of values to the attribute? – Adam Ralph Oct 12 '11 at 05:26
  • @Jaggu, If you want to send them as a String, you'll have to type them as strings or find some other way that doesn't involve a function call. If you want to sent the combined value as a number, you can use `Enum.A | Enum.B`. – Hand-E-Food Oct 12 '11 at 05:32
  • @AdamRalph, I didn't understand what was meant by list in this context until now. The first block of code works for a list provided the attribute is expecting that format. – Hand-E-Food Oct 12 '11 at 05:34
  • By List I meant I have a `List enums;` in my attribute and I can pass in that from consumer. But that is not possible. The link that Adam provided solved the issue where one can pass in array using params. – Jaggu Oct 12 '11 at 05:41
  • Okay, I misunderstood the question. – Hand-E-Food Oct 12 '11 at 06:06