Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum-like class

I am looking for a best practice on how to create enum-like class that instead of numbers contains string values. Something like this:

public static class CustomerType
{
  public static string Type1 = "Customer Type 1";
  public static string Type2 = "Customer Type 2";
}

I would use this class throughout application as a value for all cases where I need CustomerType. I cannot use Enum because this is legacy system, and values like this are hardcoded everywhere, I am just trying to centralize them in one place.

Question is, in above example, should I use for declaring a variable:

  1. static read-only keyword
  2. const keyword
  3. or just static

What would be a best practice to set these kinds of classes and values?

like image 585
Andrija Avatar asked Feb 19 '13 06:02

Andrija


Video Answer


1 Answers

If you are using C#, Why not create an enum and set string based Description attribute for the enum values as below:

public enum CustomerType
{
    [System.ComponentModel.Description("Customer Type 1")]
    Type1,

    [System.ComponentModelDescription("Customer Type 2")]
    Type2
}

Then, you can get the Description value of enum values as below:

int value = CustermType.Type1;
string type1Description = Enums.GetDescription((CustomerType)value);

For various other ways to get the Description attribute value of the enum, please refer this SO QA

like image 167
VSS Avatar answered Sep 22 '22 14:09

VSS