3

Say I have few STATIC Defined column codes around 5 and I wish to use them in several files not by using "" strings but by calling them for example :

I wish I would have a class in where my codes would be stored and whenever I call them they are called by their values for example:

public static class ColumnCodes {
 EstimatedDelivery = "ED";
 ActualDelivery = "AD";
}

and when I call them in any other class it would be:

public void x{
  var a = ColumnCodes.EstimatedDelivery; 
  // so this would be compiled like var a = "ED";
}
Fred
  • 3,365
  • 4
  • 36
  • 57
Emad Khan
  • 51
  • 1
  • 4
  • 1
    Define them as public const string or static, your class is invalid, please look up how to define members in a class – TheGeneral Jun 22 '20 at 02:51

2 Answers2

7

You still need to define a type for the static values and if you are not planning to change them since they are static, might as well make them readonly values so other classes don't change it at any point.

public static class ColumnCodes {
   public static readonly string  EstimatedDelivery = "ED";
   public static readonly string  ActualDelivery = "AD";
}
Alejandro
  • 413
  • 3
  • 9
  • Is there any more efficient way of doing this? – Emad Khan Jun 22 '20 at 02:55
  • 7
    @EmadKhan define efficient – TheGeneral Jun 22 '20 at 02:59
  • @EmadKhan - What is the down-side that you see to this approach? – Enigmativity Jun 22 '20 at 03:35
  • I mean short hand coding, just like ENUMS, won't it be something like: `public static enum Codes { EstimatedDelivery = "ED", ActualDelivery = "ED", }` And then on calling we simply call `Codes.EstimatedDelivery` // which would produce "ED" in the variable – Emad Khan Jun 22 '20 at 03:36
  • I am looking to RESHARP this code, I have no issues in duplicating each line but If I may get a short way then that would add a charm. – Emad Khan Jun 22 '20 at 03:37
  • @EmadKhan Enums don't work like that, they are best used to pair int (or db ids for example) to a strongly typed name that can be referenced through code instead of using numbers. You should look at this post as someone had that exact question about enums and string types - https://stackoverflow.com/a/5674697/8161471 – Alejandro Jun 22 '20 at 03:44
4

Using the reserved word CONST.

public static class ColumnCodes 
{
   public const string EstimatedDelivery = "ED";
   public const string ActualDelivery = "AD";
}