Question

Here is the code I would like to use:

public enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };

[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }

EnumHelper looks like:

[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
    public Type MyEnum { get; set; }
    public EnumHelper(Type enum)
    {
        MyEnum = enum;
    }
}

The error I get on EnumHelper(Days) is that "Enum Name not valid at this point". Am I doing something wrong, or can this not be done?

MORE INFO

I am trying to pass the Enum (Days), and randomly get back one of the values.

NEVERMIND: I was over-complicating this part.

Was it helpful?

Solution

The parameters in Attributes can be only constants. If you want pass the enum type you must pass only the type:

[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }


[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
    public Type MyEnum;
    public EnumHelper(Type enum)
    {
        MyEnum = enum;
    }
}

OTHER TIPS

You're trying to pass a type name as if it were an argument value. You can't do that. However, you can do:

[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
    public Type EnumType;
    public EnumHelper(Type enumType)
    {
        EnumType = enumType;
    }
}

...

[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }

However:

  • I wouldn't personally make EnumType a public field; make it a property.
  • There's currently no validation that EnumType is actually an enum. You can't do it at compile-time, but you could do it at execution time.
  • For the sake of convention, it should be called EnumHelperAttribute (or something more descriptive, really) - this isn't causing the error, but it's more idiomatic
  • I'm not really sure I see the benefit... you can find the type of the property from the metadata already; what do you think the attribute is actually buying you?

If you could let us know what you're trying to accomplish, we may be able to be more useful to you.

The parameter should be an enum value, not an enum type, like:

[EnumHelper(Days.Sat)]

Just wanted to add how I ran into this and fixed it. I had my property named the same as my enumeration. The code would compile and run, but I was getting a the red line error message in the IDE. Changing the name of the property to something unique cleared the message.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top