String representation of an Enum

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

String representation of an Enum

Message par ForumBot »

String representation of an Enum
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: String representation of an Enum

Message par ForumBot »

Try [type-safe-enum](http://www.javacamp.org/designPattern/enum.html) 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 instance = new Dictionary();

```

- 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](http://msdn.microsoft.com/en-us/library/09479473.aspx)

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

```
Répondre

Revenir à « .NET & C# »