0

I implemented Custom Attributes for enum using this article, everything is fine with hard coding values, but I need to pass the parameters in run time, for example:

enum MyItems{
    [CustomEnumAttribute("Products", "en-US", Config.Products)]
    Products
}

The Config.Products (bool value) is the problem, the error is:

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

Is there any way to fix this?

Update

The enum (MyItems in this case) have 20 items, each item must have that custom attribute, then I want to generate menu from the Enum's items, depended on Culture I getting the matched title, also depended on Config, I decided to show/hide the item from the menu (in fact if Config.X == false, I don't add the item to the menu)

Also, for Config, I have another system and I wanna sync that system with the menu, that is the reason that I wanna get the Config.X in run-time.

Thanks!

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64

2 Answers2

0

You could create an extension method

public string GetConfigValue(this MyItems myItem)
{
    return Config.GetType().GetProperty(myItem.ToString()).GetValue(Config, null);
}

This uses reflection to access the relevant property on the Config object. In the example you give, if myItem = Products then you can call

myItem.GetConfigValue()

And it should return the value of Config.Products

Related SO Questions:


Based on your update, I'd suggest this even more. Attributes must be constant values at compile time (hence the error you're getting). Even if you do not go the extension method route, you absolutely need some sort of method.

Community
  • 1
  • 1
Vlad274
  • 6,514
  • 2
  • 32
  • 44
0

No way to fix this, it's a limitation of attributes.

You can use static readonly fields in case you need a fixed set of objects with behaviour:

public class MyItems
{
    public string Name { get; private set; }

    public string Locale { get; private set; }

    readonly Func<OtherThing> factory;

    public static readonly MyItems Products = new MyItems("Products", "en-US", () => Config.Products);
    public static readonly MyItems Food = new MyItems("Food", "en-GB", () => Config.FishAndChips);

    private MyItems(string name, string locale, Func<OtherThing> factory)
    {
        this.Name = name;
        this.Locale = locale;
        this.factory = factory;
    }

    public OtherThing GetOtherThing() {
        return factory();
    }
}

See another answer for a more complete example: C# vs Java Enum (for those new to C#)

Community
  • 1
  • 1
George Polevoy
  • 7,450
  • 3
  • 36
  • 61