There is a property public int Time { get; set; }, public int Time { get; set; }, public int Time { get; set; }, which is used in the constructor

 public Person(string name, int time) { Name = name; Time = time; } 

I want to set the value of this property through the console firstPerson.Time = Int32.Parse(Console.ReadLine()); Is it possible to set valid values ​​for Time so that when entering numbers outside the range, a message appears about this?

    1 answer 1

     Person firstPerson = new Person { Name = "First", Time = 1 }; bool isSuccess = false; while (!isSuccess) { try { int n = Int32.Parse(Console.ReadLine()); if (n > 0 && n < 100) // требуемое условие { firstPerson.Time = n; isSuccess = true; } else { Console.WriteLine("Введенное число не удовлетворяет критериям."); } } catch (Exception e) { Console.WriteLine(e.Message); } } 
    • one
      If the value is entered from the console, it is reasonable to use TryParse instead of Parse and not catch an exception. - VladD
    • @VladD, and it’s impossible to implement setters for autostarting yourself? - Grundy
    • @Grundy: No, but it can be converted into non-proprietary. - VladD
    • @VladD, but then you have to add the private field yourself? - Grundy
    • @Grundy: yep. But this is one line of code :) - VladD