Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Attribute - getting "not a valid named attribute argument" for an enum

Why do i get this message when i try to use the MultiselectComperer value like this:

[Display(ResourceType = typeof(OrdersManagementStrings), Name = "PrintSettings")]
[FilterAttribute(IsMultiselect = true, MultiselectComperer=FilterAttribute.eMultiselectComperer.Or)]
public ePrintSettings PrintSettings { get; set; }

Here is the code of the custom attribute ... all emuns are public .. and yet i get this message:

'MultiselectComperer' is not a valid named attribute argument because it is not a valid attribute parameter type ....

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public sealed class FilterAttribute : Attribute
{
    public enum eMultiselectComperer
    {
        Or,
        And
    }

    public bool IsMultiselect { get; set; }

    public eMultiselectComperer? MultiselectComperer { get; set; }
}
like image 683
Mortalus Avatar asked Jan 11 '23 13:01

Mortalus


1 Answers

The problem is that the MultiselectComperer property is nullable. The compiler is complaining because unfortunately you can't make a constant of a nullable type. If you make it non nullable, your class will work just fine.

If you need to represent an third value to the eMultiselectComperer, enum other than Or and And you can create a third enum value as the default value for that enum, like this:

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public sealed class FilterAttribute : Attribute
{
    public enum eMultiselectComperer
    {
        Unspecified = 0, 
        Or,
        And
    }

    public bool IsMultiselect { get; set; }

    public eMultiselectComperer MultiselectComperer { get; set; }
}

This way, if the user doesn't specify a value for the MultiselectComperer property when declaring the attribute, it will default to Unspecified (or whatever you prefer to call it).

like image 124
p.s.w.g Avatar answered Feb 04 '23 06:02

p.s.w.g