Home > other >  Set custom attribute value from Enum in C#
Set custom attribute value from Enum in C#

Time:11-24

I have one custom attribute like below,

   [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
    public class SetValForAll : Attribute
    {
        public string Limit { get; set; }

        public SetValForAll(string limit)
        {
            Limit = limit;
        }
    }

While using this attribute(SetValForAll) I want to pass the value of Limit using one Enum but it is showing error 'An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type'

My Enum is like below,

        public enum LimitEnum
        {
            max,
            min
        }

The below piece of code is throwing error in the attribute line.

[SetValForAll(LimitEnum.max.ToString())]
public class UsingTheAttributeHere
{
}

How I can take value from LimitEnum while using SetValForAll attribute, rather than passing hardcoded string?

CodePudding user response:

You could use the nameof expression that will get you the enum as a string constant. [SetValForAll(nameof(LimitEnum.max))]

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/nameof

CodePudding user response:

Well, you can't pass non-constant strings in attribute values. Why don't you use your enum type instead of string for your property? You can use LimitEnum to pass in the constructor.

   [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
    public class SetValForAll : Attribute
    {
    public LimitEnum Limit { get; set; }

    public SetValForAll(LimitEnum limit)
    {
        Limit = limit;
    }
    }

and use it like this :

[SetValForAll(LimitEnum.max)]
  • Related