Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public Enumeration with only string values

Tags:

c#

enumeration

I'm always confused which kind of enumeration I should use. A hashtable, an enum, a struct a dictionary, an array (how oldschool), static strings...

Instead of using strings in my code I want to use a beautiful enum like so:

public enum MyConfigs
{
    Configuration1,
    Configuration2
}

Problem is that I don't always want to convert my enum toString() as I'm not interested in the index representation of the enum.

What is the best way to represent a public enumeration of string based values?
In the end I would love to end up with using MyConfigs.Configuration1 where needed in my code.

like image 441
Dennis G Avatar asked Jun 08 '26 15:06

Dennis G


2 Answers

I prefer defining "grouped" constants as static members of a dummy static class, like so:

public static class FieldNames
{
    public const string BRANCH_CODE = "_frsBranchCode";
    public const string BATCH_ID = "_frsBatchId";
    public const string OFFICE_TYPE = "_frsOfficeType";
}

But of course they are not "enumerable" directly, so you can't foreach over them unless you provide a static array too:

public static string[] AllFieldNames
{
    get
    {
        return new string[]
        {
            FieldNames.BRANCH_CODE,
            FieldNames.BATCH_ID,
            FieldNames.OFFICE_TYPE
        };
    }
}
like image 62
Ishmaeel Avatar answered Jun 11 '26 03:06

Ishmaeel


public static class MyConfigs
{
    public const string Configuration1 = "foo",
                        Configuration2 = "bar"
}

This is then pretty-much identical to how enums are implemented (ignoring the whole "it must be an integer" thing).

like image 44
Marc Gravell Avatar answered Jun 11 '26 05:06

Marc Gravell