开发者

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

Is it OK to use Structs as Data libra开发者_StackOverflowry 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;

}


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()
  {

  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜