CSharpNoob
CSharpNoob

Reputation: 1301

Coding : Using Struct as a DataUtility/Library for Hardcode values (Constants)

Is it OK to use Structs as Data library for hardcoded values? Sometimes we can't avoid hardcoding somethin althought it's better to put it on something like xml file or a database table, but sometimes it's not possible for some reasons.

 public struct BatchStatus
 {
    public const string Submitted = "0901XX";
    public const string Active = "62783XY";
    public const string Inactive = "S23123";
 }

then I use it like this

 switch (batchStatus) // enums doesnt work in switch case
{
     case BatchStatus.Submitted:
         new Batch().Submit(); break;
    case BatchStatus.Inactive:
        new Batch1().Activate(); break;
    case BatchStatus.Active
        new Batch2().Deactivate(); break;

}

Upvotes: 2

Views: 1853

Answers (1)

Chris Taylor
Chris Taylor

Reputation: 53709

If you are using C# 2.0 and above, you should rather use a static class. Prior to C# 2.0, you can use a class an just add a private default constructor to ensure that the class in never instantiated.

C# 2.0 and later

public static class BatchStatus
{
  public const string Submitted = "0901XX";
  public const string Active = "62783XY";
  public const string Inactive = "S23123";
}

C# 1.0 - 1.2

public class BatchStatus
{
  public const string Submitted = "0901XX";
  public const string Active = "62783XY";
  public const string Inactive = "S23123";

  private BatchStatus()
  {

  }
}

Upvotes: 2

Related Questions