Created
March 24, 2016 03:12
-
-
Save Blizzardo1/d4004e375525f2a669da to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Blizzeta { | |
public class Prompt { | |
public static int X; | |
public static int Y; | |
public static void Main(string[] args) { | |
RepeatUntilYes(); | |
} | |
private static string PromptForString(string message) { | |
Console.Write(message); | |
return Console.ReadLine(); | |
} | |
private static int PromptForInt(string message) { | |
string x = PromptForString(message); | |
int i = 0; | |
int.TryParse(x, out i); | |
return i; | |
} | |
private static bool PromptForBool(string message) { | |
string answer = PromptForString(message).ToLower(); | |
if(answer == "yes" || answer == "y") { | |
return true; | |
} | |
else if(answer == "no" || answer == "n") { | |
return false; | |
} | |
else { | |
Console.WriteLine("Must be a (Y)es/(N)o answer\r\n"); | |
return PromptForBool(message); | |
} | |
} | |
private static void RepeatUntilYes() { | |
X = PromptForInt($"How many horizontal screen spaces shall we have?[default:{gridSzX}] "); | |
Y = PromptForInt($"How many vertical screen spaces shall we have?[default:{gridSzY}] "); | |
if(PromptForBool("Are these the correct values? ")) | |
return; | |
RepeatUntilYes(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pointlessly Doing Things
No need to initialize
i
on line 20. E.g.,My argument against doing unnecessary things is that the reader of the code will assume you had some reason to perform the unnecessary action and spend a lot of time trying to figure out why you did it when it was totally unnecessary. In C#, any method accepting an
out
parameter will always write to the passed argument if it completes without throwing an example. For example, the following won’t compile because it doesn’t always assign tox
when it runs to completion:Thus, we know that
int.TryParse()
will unconditionally assign to itsout
variable and shouldn’t preinitialize it. The docs even specify that0
is the value assigned when the conversion fails, though most of the time you would need to check the return value to detect conversion failure.Culture
Unless you’re going to load the strings
"yes"
,"y"
,"no"
, and"n"
from some localization source, it’s probably better to usestring.ToLowerInvariant()
thanstring.ToLower()
. I’ve never really played with locales much, but it’s possible that whatever locale the user has chosen will have"YES".ToLower() == "YES"
rather than"YES".ToLower() == "yes"
or something like that.