String Representation of an Enum

String representation of an Enum

Try type-safe-enum pattern.

public sealed class AuthenticationMethod {

private readonly String name;
private readonly int value;

public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS");
public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS");
public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN");

private AuthenticationMethod(int value, String name){
this.name = name;
this.value = value;
}

public override String ToString(){
return name;
}

}

Update
Explicit (or implicit) type conversion can be done by

  • adding static field with mapping

    private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();
    • n.b. In order that the initialisation of the the "enum member" fields doesn't throw a NullReferenceException when calling the instance constructor, be sure to put the Dictionary field before the "enum member" fields in your class. This is because static field initialisers are called in declaration order, and before the static constructor, creating the weird and necessary but confusing situation that the instance constructor can be called before all static fields have been initialised, and before the static constructor is called.
  • filling this mapping in instance constructor

    instance[name] = this;
  • and adding user-defined type conversion operator

    public static explicit operator AuthenticationMethod(string str)
    {
    AuthenticationMethod result;
    if (instance.TryGetValue(str, out result))
    return result;
    else
    throw new InvalidCastException();
    }

Associating string representations with an Enum that uses integer values?

This can be done with the stdlib Enum, but is much easier with aenum1:

from aenum import Enum

class Fingers(Enum):

_init_ = 'value string'

THUMB = 1, 'two thumbs'
INDEX = 2, 'offset location'
MIDDLE = 3, 'average is not median'
RING = 4, 'round or finger'
PINKY = 5, 'wee wee wee'

def __str__(self):
return self.string

If you want to be able to do look-ups via the string value then implement the new class method _missing_value_ (just _missing_ in the stdlib):

from aenum import Enum

class Fingers(Enum):

_init_ = 'value string'

THUMB = 1, 'two thumbs'
INDEX = 2, 'offset location'
MIDDLE = 3, 'average is not median'
RING = 4, 'round or finger'
PINKY = 5, 'wee wee wee'

def __str__(self):
return self.string

@classmethod
def _missing_value_(cls, value):
for member in cls:
if member.string == value:
return member

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Using Enum values as String literals

You can't. I think you have FOUR options here. All four offer a solution but with a slightly different approach...

Option One: use the built-in name() on an enum. This is perfectly fine if you don't need any special naming format.

    String name = Modes.mode1.name(); // Returns the name of this enum constant, exactly as declared in its enum declaration.

Option Two: add overriding properties to your enums if you want more control

public enum Modes {
mode1 ("Fancy Mode 1"),
mode2 ("Fancy Mode 2"),
mode3 ("Fancy Mode 3");

private final String name;

private Modes(String s) {
name = s;
}

public boolean equalsName(String otherName) {
// (otherName == null) check is not needed because name.equals(null) returns false
return name.equals(otherName);
}

public String toString() {
return this.name;
}
}

Option Three: use static finals instead of enums:

public final class Modes {

public static final String MODE_1 = "Fancy Mode 1";
public static final String MODE_2 = "Fancy Mode 2";
public static final String MODE_3 = "Fancy Mode 3";

private Modes() { }
}

Option Four: interfaces have every field public, static and final:

public interface Modes {

String MODE_1 = "Fancy Mode 1";
String MODE_2 = "Fancy Mode 2";
String MODE_3 = "Fancy Mode 3";
}

How to convert an enum type variable to a string?

There really is no beautiful way of doing this. Just set up an array of strings indexed by the enum.

If you do a lot of output, you can define an operator<< that takes an enum parameter and does the lookup for you.

What is idiomatic way to get string representation of enum in Go?

The second one is more idiomatic because it satisfies Stringer interface.

func (day Day) String() string  {
...
}

We declare this method on the Day type not *Day type because we are not changing the value.

It will enable you to write.

fmt.Println(day)

and get the value produced by String method.

Getting value of enum on string conversion

You are printing the enum object. Use the .value attribute if you wanted just to print that:

print(D.x.value)

See the Programmatic access to enumeration members and their attributes section:

If you have an enum member and need its name or value:

>>>
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1

You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:

class D(Enum):
def __str__(self):
return str(self.value)

x = 1
y = 2

Demo:

>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1

Enum ToString with user friendly strings

I use the Description attribute from the System.ComponentModel namespace. Simply decorate the enum:

private enum PublishStatusValue
{
[Description("Not Completed")]
NotCompleted,
Completed,
Error
};

Then use this code to retrieve it:

public static string GetDescription<T>(this T enumerationValue)
where T : struct
{
Type type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
}

//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

if (attrs != null && attrs.Length > 0)
{
//Pull out the description value
return ((DescriptionAttribute)attrs[0]).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}

How to get an enum value from a string value in Java

Yes, Blah.valueOf("A") will give you Blah.A.

Note that the name must be an exact match, including case: Blah.valueOf("a") and Blah.valueOf("A ") both throw an IllegalArgumentException.

The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType shows both methods.

string representation of an enum (estring)?

Would it be an option not to use enum and use structs instead?

struct FooEnum
{
private int value;
private string name;
private FooEnum(int value, string name)
{
this.name = name;
this.value = value;
}

public static readonly FooEnum A = new FooEnum(0, "Foo A");
public static readonly FooEnum B = new FooEnum(1, "Foo B");
public static readonly FooEnum C = new FooEnum(2, "Foo C");
public static readonly FooEnum D = new FooEnum(3, "Foo D");

public override string ToString()
{
return this.name;
}

//TODO explicit conversion to int etc.
}

You could then use FooEnum like an enum with an own ToString() overload:

FooEnum foo = FooEnum.A;
string s = foo.ToString(); //"Foo A"


Related Topics



Leave a reply



Submit