My IF property is being ignored in my class when i use it

Viewed 55
public class Irritante : Child   
{
    /*Fields*/
    private int ir_numeroBirras;
    private double ir_mediaBirras; 

    /*Properties*/
    public int NumeroBirras
    {
        get { return ir_numeroBirras; }
        set { if (value > 0) ir_numeroBirras = value; }
    }
    public double MediaBirras
    {
        get { return ir_mediaBirras; }
        set { ir_mediaBirras = value; }
    }
    //Constructor
    public Irritante(string nome, int idade, int numBirras, double mediaDasBirras) : base(nome, idade)
    {
        NumeroBirras = numBirras;
        ir_mediaBirras = mediaDasBirras;
    }

When i try to use the contructor Irritante with the property NumeroBirras it is ignoring the if(value>0) This means i can still add a 0 to this field with client code, which i should not be able to, any tips? i cant find it anywhere

1 Answers

The default value of ir_numeroBirras is 0. You can't put a 0 using the property. But if you test using a 0 as parameter value, you are being fooled by the default value.

If you're talking about you shouldn't put a 0 in the parameter of Irritante ctor, that's quite different

public Irritante(string name, int idade, int numBirras, double mediaDasBirras) : base(nome, idade) 
{
   if(numBirras < 1) throw new ArgumentOutOfRangeException(nameof(numBirras), "Hey, you can't drink 0 beers");
   ir_numeroBirras = numBirras;
   ir_mediaBirras = mediaDasBirras;
}
Related