views:

342

answers:

3

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.

A: 

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

[EnumHelper(Days.Sat)]
Philippe Leybaert
That won't work because of the boxing conversion from `Days.Sat` to `Enum`.
Jon Skeet
It won't? I always thought passing constant values as value types worked with attributes.
Philippe Leybaert
+5  A: 

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;
    }
}
TcKs
+7  A: 

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.

Jon Skeet