How to activate a setter method without input in the main program code?
I'm working on a program that needs to check if a value is an integer before applying it to an attribute of a class. This must be done in a setter ("set") method.
internal class Dummy {
private int number;
public int Number {
get { return number; }
set { Console.Write("Input number: "); if (int.TryParse(Console.ReadLine(), out value) == true) { number = value; Console.WriteLine("The number is " + number + "."); } else { Console.WriteLine("That is not a number."); } }
}
}
I tried to make the input in the main program a string (objectName.Number = Console.ReadLine();) instead of an int (objectName.Number = Convert.ToInt32(Console.ReadLine()):), but this obviously gave me an error.
I've then tried to just make the input an int, but use a string input when running the program. This would lead to a crash.
The only way I could make this work was for the user to enter a "useless" number (for the first "main program" input to be discarded) and then input the right one when prompted with "Input number: "; but this "solution" looks and feels clunky.
I'm open to different ways of doing this, but remember, the setter absolutely must be the code that checks whether the value is an int (and then apply it accordingly).
Comments
Post a Comment