-2

I have certain class variables in a class that I would like to do somethin whenever they are set (check valid, pad with spaces etc). I have never used get set before was wondering if using those would be right approach but I am getting stack overflow error.

    public string DELIVERY_DATE
    {
        get { return DELIVERY_DATE; }
        set 
        {
            DELIVERY_DATE = checkDate(value, "yyyyMMdd");
        }
    }
Lightsout
  • 3,454
  • 2
  • 36
  • 65
  • 2
    `DELIVERY_DATE` is a property. You need a backing field (i.e., a variable) to use in the setter and getter. See [this](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties) for reference. – 41686d6564 stands w. Palestine Nov 08 '21 at 23:31
  • You're setting the variable in the setter for the variable, resulting in infinite recursion... Use a separate var for the value. – ikegami Nov 08 '21 at 23:31
  • Also you should really be using standard C# naming conventions. For your enjoyment https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions – TheGeneral Nov 08 '21 at 23:33
  • Setters and getters are just methods that are generated by the compiler, you can do anything in them you like, ideally you would not want to do anything heavy (or asynchronous work), however a small validation or mutation is fine. As to where these lines are and how much validation (such as throwing) is best practice is opinionated. – TheGeneral Nov 08 '21 at 23:41

2 Answers2

1

you have a recursion here. Delivery date calls itself. try this

private string _DELIVERY_DATE
public string DELIVERY_DATE
   {
       get { return _DELIVERY_DATE; }
       set 
       {
           _DELIVERY_DATE = checkDate(value, "yyyyMMdd");
       }
   }
Serge
  • 40,935
  • 4
  • 18
  • 45
  • 1
    Is this a good method to do some routine before setting the variable though? – Lightsout Nov 08 '21 at 23:37
  • @bakalolo Yes, usually it is using for validation. The code should be as clouse to data it validates as possible. This is the most closed. For example you can check if delivery date should be in the future (or past) and fixed it or set to null or set it as error (since it is a string). – Serge Nov 08 '21 at 23:59
0

Properties are valid way to do this. But you use it inappropriately:

class myClass {

   // here will be stored the value
   private string deliveryDate;
   public string DELIVERY_DATE
   {
      // this "method" will be called 
      // when e.g. x = thisClass.DELIVERY_DATE line executed
      get 
      { 
         return deliveryDate; 
      }
      // this "method" will be called 
      // when e.g. thisclass.DELIVERY_DATE = "20211108" executed
      set 
      {
         deliveryDate = checkDate(value, "yyyyMMdd");
      }
   }

}

Here are MS docs: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties

cly
  • 661
  • 3
  • 13