How implement a string based enum

  • Thread starter Thread starter Soeren S. Joergensen
  • Start date Start date
S

Soeren S. Joergensen

Hi,

I need to have something like (wich as written of course is not possible)

public enum CountryType : String
{
USA = "US",
UnitedKingdom = "UK",
Germany = "DE",
Denmark = "DK"
}

Well, it has to be a sealed class of some sort with a lot of static fields -
but how do i get same functionallity as with a regular enum

Kr.
Soren
 
Soeren said:
I need to have something like (wich as written of course is not possible)

public enum CountryType : String
{
USA = "US",
UnitedKingdom = "UK",
Germany = "DE",
Denmark = "DK"
}

Well, it has to be a sealed class of some sort with a lot of static fields
- but how do i get same functionallity as with a regular enum

I guess that depends on what functionality exactly you mean - it won't be
possible to reproduce the enum functionality in every detail, because your
class won't really be an enum, whatever you do.

But you could do something like this to start with:

public static class Country {
private Country(string stringValue) {
this.stringValue = stringValue;
}
private string stringValue;

public static readonly Country USA = new Country("US");
public static readonly Country UnitedKingdom = new Country("UK");
public static readonly Country Germany = new Country("DE");
public static readonly Country Denmark = new Country("DK");
}


Oliver Sturm
 
i achive something similar by creating static fields in a class like this:

public sealed class CountryType
{
public static string USA { get { return "US"; } }
public static string UnitedKingdom { get { return "UK"; } }
public static string Germany { get { return "DE"; } }
}
 
Back
Top