Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage a list of Constants

Tags:

c#

In several projects, we have a list of constant values in the database. These each have a table, name, and a GUID value. For example a Ticket Status table might have 3 values, "Open", "Closed" and "Hold". In our C# code a framework generates a C# file, as follows.

public class TicketStatus { 
     public static Guid Open =  new Guid( "7ae15a71-6514-4559-8ea6-06b9ddc7a59a");
     public static Guid Closed =  new Guid( "41f81283-57f9-4bda-a03c-f632bd4d1628");
     public static Guid Hold =  new Guid( "41bcc323-258f-4e58-95be-e995a78d2ca8");
}; // end of TicketStatus

This allows us to write some clean(ish) code that sets ticket status as follows ticket.strStatus = TicketStatus.Open.ToString();

While this works: - It produces pretty clean C# code that's easy to ready and maintain - It's supported by Intellisense

it's still clumsy, in that - We have to continually convert to string for many operations - The use of GUIDs seems like overkill. - We cannot write a "normal" switch statement

// This won't compile
        switch( strStatus ) {
        case TicketStatus.Open:
        case TicketStatus.Closed:
        // do some stuff.
        break;
        }

The code was originally implemented with a bunch of GUIDs, to manage the case when a database would return the values in all upper case.

The question: What's the best way to code these constant values, so that it supports IntelliSense and switch statements?

like image 896
William Walseth Avatar asked Nov 22 '25 10:11

William Walseth


1 Answers

Thanks Kirk, Here's the string solution that I'm using.

public static class TicketStatus {
    public const string Open = "7ae15a71-6514-4559-8ea6-06b9ddc7a59a";
    public const string Closed = "41f81283-57f9-4bda-a03c-f632bd4d1628";
    public const string Hold = "41bcc323-258f-4e58-95be-e995a78d2ca8";
}; // end of TicketStatus

string strTemp = TicketStatus.Open;
switch (strTemp) {
    case TicketStatus.Open:
        strTemp = "Jackpot";
        break;
}
like image 100
William Walseth Avatar answered Nov 24 '25 23:11

William Walseth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!