Shane Grant
Shane Grant

Reputation: 2654

C# Enum Question

I need to make an enum with one of the values = 50/50

Is this not possible? Visual Studio doesn't seem to like it.

I may have to make this field a database lookup it seems.

Please let me know.

Upvotes: 0

Views: 313

Answers (6)

dhinesh
dhinesh

Reputation: 4764

You can use the Description Attribute to store the custom value of the enum in the Description and then use it.

the Enum:

public enum MyEnum
{
    [Description("50/50")]
    Enum1 = 1,

    [Description("Whatever")]
    Enum2 = 2,
}

Method to read the custom value stored in Description attribute using reflection.

private static string GetEnumCustomValue(Enum value)
{
   FieldInfo enumField = value.GetType().GetField(value.ToString());
   var attributes = 
      (DescriptionAttribute[])enumField.GetCustomAttributes(typeof(DescriptionAttribute)), false);
   if (attributes.Length > 0)
   {
      return attributes[0].Description;
   }
   return value.ToString();
}

Upvotes: 3

Oliver
Oliver

Reputation: 45071

dhinesh give already a good tip by using the Description attribute.

I would recommend the following enum

public enum Chances
{
    [Description("No guess available")]
    NotDefined = 0,

    [Description("No chance")]
    None,

    [Description("50/50")]
    FiftyFifty,

    [Description("100%")]
    Always        
}

To get afterwards the description out of it you should take a look into these question:

Upvotes: 0

Dan Tao
Dan Tao

Reputation: 128317

If you want the NAME of your value to be 50/50, you're out of luck. You can however define a value whose name is FiftyFifty, which (in my opinion) is just as descriptive a name.

Upvotes: 1

Tom
Tom

Reputation: 836

C# enumerations compile out as sealed classes, inheriting from Enum, with public static fields carrying the name of your enumeration members, thus, you're asking the compiler to name fields the enum values or 50/50 in your case.

Enumeration values carry the same restrictions as properties and fields when it comes to naming.

Upvotes: 5

Ed Swangren
Ed Swangren

Reputation: 124622

Yup, sure is possible

enum SomeEnum
{
    Value = 1 // 50/50!
}

Enum values are constant integral types.

Upvotes: 1

Brent Arias
Brent Arias

Reputation: 30155

A "50/50" value? You mean a string value? No, C# cannot do that.

Upvotes: 0

Related Questions