Home > Blockchain >  How to pass comma separated value in attribute when input parameter is enum in c#
How to pass comma separated value in attribute when input parameter is enum in c#

Time:11-30

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, not one single value but comma separated value of the enum.

My Enum is like below,

public enum LimitEnum
{
    Initiated,
    InProcess,
    Done
}

If I apply the attribute in any type I am expecting comma separated value of enum like "Initiated,InProcess" will be received in the attribute

I tried below piece of code but it is showing error. How I can use the enum in attribute level to pass comma separated value?

[SetValForAll(nameof(LimitEnum.Initiated, LimitEnum.InProcess))]
public class UsingTheAttributeHere
{
}

CodePudding user response:

You can do this with a Flags enum. eg

[Flags]
public enum LimitEnum
{
    Initiated = 1,
    InProcess = 2,
    Done = 4
}

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

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

[SetValForAll(LimitEnum.Initiated | LimitEnum.InProcess)]
public class UsingTheAttributeHere
{
}

CodePudding user response:

If you really want a string in your attribute, you can use string interpolation.

[SetValForAll($"{nameof(LimitEnum.Initiated)},{nameof(LimitEnum.InProcess)}")]

But if the receiving end is going to read these as enum values anyway, you are better off using a Flags enum and passing an OR'ed value to the attribute, like in David Browne's answer.

  • Related