Skip to content

Instantly share code, notes, and snippets.

@Blizzardo1
Created March 24, 2016 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Blizzardo1/d4004e375525f2a669da to your computer and use it in GitHub Desktop.
Save Blizzardo1/d4004e375525f2a669da to your computer and use it in GitHub Desktop.
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();
}
}
}
@binki
Copy link

binki commented Mar 24, 2016

Pointlessly Doing Things

No need to initialize i on line 20. E.g.,

int i;
int.TryParse(x, out i);

return i;

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 to x when it runs to completion:

class Blah
{
    static void MyMethod(string s, out int x)
    {
        if (s.StartsWith("abc"))
            x = 5;
    }
}

Thus, we know that int.TryParse() will unconditionally assign to its out variable and shouldn’t preinitialize it. The docs even specify that 0 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 use string.ToLowerInvariant() than string.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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment