I suggest you ...

String Enum for both C# and VB

The underlying type for an Enum is integer based; but I was wondering if it were possible to have a Enum that were String based. Not sure if it's even possible make sense; but it would save some time creating wrapper classes for String constants.

106 votes
Vote
Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
You have left! (?) (thinking…)
Tyrone Davis, Jr. shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

7 comments

Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
Submitting...
  • Vasim Hanna-Salem commented  ·   ·  Flag as inappropriate

    In C# 6 you can do this for now:

    public static class Fruits
    {
    public static string Apple => nameof(Apple);
    public static string Orange => nameof(Orange);
    public static string Banana => nameof(Banana);
    }

  • Holger M. Rößler commented  ·   ·  Flag as inappropriate

    @Tired:
    You can do like this to get a string of a enum constant:
    string acceptedCard = AcceptedCreditCards.mastercard.ToString();

    @Tim: I'm not sure why you need methods inside an enum but you can add Methods to an enum by using extension methods. Not nice, but works.

  • Tim commented  ·   ·  Flag as inappropriate

    Enums should be able to be of any type and contain methods as they do in Java. The current implementation in C# sucks.

  • Qwertie commented  ·   ·  Flag as inappropriate

    My "Symbol" class, based on the idea of :symbols in Ruby, is basically a string-based enum with fast integer-like performance: http://www.codeproject.com/Articles/34753/Symbols-as-extensible-enums

    This concept would be a lot easier to use with compiler support. I'd really, REALLY love to see methods that take Symbol arguments, with an inline list of allowed symbols. For example, methods like the following are clumsy to define:

    public string[] Split(char[] separator, StringSplitOptions options);

    it's clumsy because you have to define the "StringSplitOptions" as a completely separate entity from the class that contains the Split() method. Plus you may have to write separate documentation for the darn thing. Plus the user has to write "StringSplitOptions.RemoveEmptyEntries" which is incredibly long-winded.

    For all these reasons, people often use boolean parameters, which often leads to less readable method calls and causes trouble when you need to add a third possible behavior to your method.

    I imagine a definition like this instead:

    public string[] Split(char[] separator, [OneOf(:RemoveEmptyEntries, :KeepEmptyEntries)] Symbol option);

    If the user tries to pass an illegal option (and this is known at compile-time), the compiler would issue a warning or error.

Feedback and Knowledge Base