Im pretty new to programming so i dont know much myself other than what we've done in my into c# class so far but i've looked pretty much everywhere for a way to condense readlines so that the program will read many inputs in a row without having to code a readline for every variable the user is inputting for.
Console.WriteLine("Enter ID for Jane Doe: ");
c.ID = Console.ReadLine();
Console.WriteLine("Enter Insurance Name for Jane Doe: ");
c.Insurance = Console.ReadLine();
Console.WriteLine("Enter Height(In.) for Jane Doe: ");
c.Height = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Weight(lbs.) for Jane Doe: ");
c.Weight = Convert.ToSingle(Console.ReadLine());
Console.WriteLine("Enter Health Status for Jane Doe: ");
c.HealthStatus = Console.ReadLine();
This example is from some homework from a little bit ago but it bothered me that I couldn't find a way to condense the code. Basically I want to be able to ask for all the information in one writeline and then only use one readline/other method for the input of each variable where the user types the info for one variable, hits enter, then repeats however often is needed. Is there any way to do that or do i just have to deal with the repetition?
For occasional use where readability is preferred over compactness, you might try something like this to do a simple multi-field parse of a single line of input.
Thats it I'm afraid! The best way anyway, you can always read one string then split it but that would involve extra handling and more time consuming.. that way would be
The way you have it you could do extra handling such as
This would keep your users in a loop until they enter a valid height
Honestly, to the best of my knowledge there isn't much better. You could try this for readability/reusability
Simple and reusable. Not perfect though.
In general, you need to just deal with the repetition. Its clear, easy to debug, and its really not that bad.
Now, you could do this:
Which you would then create like so:
Then you could iterate through them:
But in all reality, that removes a lot of readability for the sake of slightly smaller code. I would use such a pattern in a different context perhaps, but here, your code is fine.
If I was asking many questions and they were for a handful of data type responses I'd probably go with the following:
with supporting methods like below
Simple and readable. I wouldn't bother unless there were several questions being asked though. Also can include in the "Ask" methods validation code for the data type you expect. For example if you expect an int and get a string you could give the user a chance to re-type it, or throw an error back to them.