0

I want to ask that can I validate data if I use the getters and setters short hand

public int GrossSallery { get;set; }

Actually I don't want users to come and just provide some random input. I know I can use the extended properties like

public int GrossSallery
    {
        get
        {
            return this.tax;
        }
        set
        {
            if (value <= 0)
            {
                return;
            }
            this.tax = value;
        }
    }
Muhammad Saqlain
  • 2,112
  • 4
  • 33
  • 48
  • Possible solution is creating a custom validation class inherited from the [ValidationAttribute Class](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationattribute?redirectedfrom=MSDN&view=net-7.0). Usually this solution is using when required to validate a few properties with similar logic. See [Validating properties in c#](https://stackoverflow.com/q/4946227/6630084) – Jackdaw Mar 30 '23 at 11:57
  • You might want to rename your property GrossSalary. – Palle Due Mar 30 '23 at 11:58
  • depending on your use-case you could validate using data annotations and validation attributes e.g. https://stackoverflow.com/questions/7926693/validation-using-attributes – vhr Mar 30 '23 at 11:58
  • Simpler syntax is in the language to be used on simpler problems. If you need something more complex then use the facilities also in the language that help in those situations. Don't try to hard to come up with something clever surrounding a simple syntax to attach somehow the more complex stuff. Applied here using explicit getter/setters is not "bad" when you need something to do something in there. – Ralf Mar 30 '23 at 12:33
  • One comment about the provided code. When the value is zero or less, you do a direct return. This means that the caller never knows when the value actually is set or not. Either throw an OutOfRangeException or create a method to `bool TrySetGrossSallery(value)` – Jeroen van Langen Mar 30 '23 at 12:37

2 Answers2

1

As far as I know this isn't possible without a private field. But you can shorten your example like this.

private int tax;
public int GrossSallery
{
    get=> tax;
    set => tax = value <= 0 ? tax : value;
}
Marvin Klein
  • 1,436
  • 10
  • 33
0

I recommend using a method instead of the setter because a property setter should not contain logic. Additionally make the setter private so it can only be set using the method.

Could look like this

public int GrossSalary { get; private set; }  

public void TrySetGrossSalary(int grossSalary)
{
   //Validation and setting property
}
Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
  • "because a property setter should not contain logic" - well that right there is a bold statement; it probably shouldn't have side-effects, but: *validation* logic is normal and expected in a setter – Marc Gravell Mar 30 '23 at 16:20