locked
add validation to variable declaration in C# RRS feed

  • Question

  • User-1225169881 posted

    what is the best way to add validations to variable in C# 6?

     for example, i would like to limit a double to 3 decimals, during declaartion of variable 

    Wednesday, January 25, 2017 3:22 PM

All replies

  • User281315223 posted

    for example, i would like to limit a double to 3 decimals, during declaartion of variable 

    You aren't really going to be able to limit a given value to a certain number of decimal places simply by declaring the variable. You'll likely want to add a method that would handle performing this for you whenever you set the value :

    private double _yourDouble;
    public double YourDouble {
         get { return _yourDouble; }
         set { _yourDouble= Math.Round(value, 3, MidpointRounding.AwayFromZero); }
    }

    It's important to remember that only displaying three decimal places is something that is going to be done at the "formatting" stage. That is, a double or decimal object will always contain and support the number of decimal places of precision, but if you are handling outputting it, you can format it as you like.

    Wednesday, January 25, 2017 4:26 PM