How to use expanded property in C #

5

I have a problem, I created a class containing the following property:

public class MinhaClasse
{
public int Idade {get; set;}
}

However, when I do this:

public class MinhaClasse
{
   public int Idade {
      get{
         return Idade;
      }
      set{
         if (value < 18)
            throw new Exception("Proibido para menores!");
         else
            Idade = value;
      }
   }
}

The above code does not work and I'm forced to create a private attribute to store the idade value, or at least I've done so. Is that correct? Why can not I use Idade = value ?

public class MinhaClasse
    {
       private int _idade;
       public int Idade {
          get{
             return _idade;
          }
          set{
             if (value < 18)
                throw new Exception("Proibido para menores!");
             else
                _idade = value;
          }
       }
    }
    
asked by anonymous 16.12.2017 / 22:06

1 answer

4

You have to create the private field to work, you are creating an infinite loop , because the Idade property is used to manipulate the Idade property, which will then force manipulate Idade and so it goes.

using System;

public class Program {
    public static void Main() {
        var obj = new MinhaClasse();
        obj.Idade = 20;
        Console.WriteLine(obj.Idade);
        obj.Idade = 10;

    }
}

public class MinhaClasse {
    private int idade;
    public int Idade {
        get => idade;
        set => idade = value < 18 ? throw new Exception("Proibido para menores!") : value;
    }
}

See running on .NET Fiddle . And in Coding Ground . Also I placed GitHub for future reference .

Whenever you cast a Exception you are doing something wrong. They even consider that this class should be abstract for anyone to use. Many people find it bad to throw an exception on a property, at least in most cases. This is controlling flow with exception .

    
16.12.2017 / 22:15