views:

333

answers:

4

How can you set a default input value in a .net console app?

Here is some make-believe code:

Console.Write("Enter weekly cost: ");
string input = Console.ReadLine("135"); // 135 is the default. The user can change or press enter to accept
decimal weeklyCost = decimal.Parse(input);

Of course, I don't expect it to be this simple. I am betting on having to do some low-level, unmanaged stuff; I just don't know how.

EDIT

I know I can replace no input with the default. That's not what I am asking about. I am trying to LEARN what's involved in achieving the behavior I described: giving the user an editable default. I'm also not worried about input validation; my question has nothing to do with that.

+3  A: 

Or... Just test the value entered, if it's empty put the default value in input.

Dani
to make it look better - you can use a property and add this in the setter....
Dani
A: 

Simple solution, if user inputs nothing, assign the default:

Console.Write("Enter weekly cost: ");
string input = Console.ReadLine();
decimal weeklyCost = String.IsNullOrEmpty(input) ? 135 : decimal.Parse(input);

When dealing with user inputs, you should expect that it might contain errors. So you could use TryParse in order to avoid an exception, if the user has not input a number:

Console.Write("Enter weekly cost: ");
string input = Console.ReadLine(); 
decimal weeklyCost;
if ( !Decimal.TryParse(input, out weeklyCost) ) 
    weeklyCost = 135;

This would be considered best-practice for handling user input. If you need to parse many user inputs, use a helper function for that. One way of doing it is to use a method with a nullable and return null if parsing failed. Then it is very easy to assign a default value using the null coalescing operator:

public static class SafeConvert
{
    public static decimal? ToDecimal(string value)
    {
        decimal d;
        if (!Decimal.TryParse(value, out d))
            return null;
        return d;
    }
}

Then, to read an input and assign a default value is as easy as:

decimal d = SafeConvert.ToDecimal(Console.ReadLine()) ?? 135;
driis
You left his fictitious parameter to `ReadLine` in place.
Adam Robinson
@Adam, thanks for pointing that out, answer edited.
driis
A: 

You can use helper method like this:

public static string ReadWithDefaults(string defaultValue)
{
    string str = Console.ReadLine();
    return String.IsNullOrEmpty(str) ? defaultValue : str;
}
SMART_n
+2  A: 

I believe that you will have manage this manually by listening to each key press:

Quickly thown together example:

   // write the initial buffer
   char[] buffer = "Initial text".ToCharArray();
   Console.WriteLine(buffer);

   // ensure the cursor starts off on the line of the text by moving it up one line
   Console.SetCursorPosition(Console.CursorLeft + buffer.Length, Console.CursorTop - 1);

   // process the key presses in a loop until the user presses enter
   // (this might need to be a bit more sophisticated - what about escape?)
   ConsoleKeyInfo keyInfo = Console.ReadKey(true);
   while (keyInfo.Key != ConsoleKey.Enter)
   {

       switch (keyInfo.Key)
       {
            case ConsoleKey.LeftArrow:
                    ...
              // process the left key by moving the cursor position
              // need to keep track of the position in the buffer

         // if the user presses another key then update the text in our buffer
         // and draw the character on the screen

         // there are lots of cases that would need to be processed (backspace, delete etc)
       }
       keyInfo = Console.ReadKey(true);
   }

This is quite involved - you'll have to keep ensure the cursor doesn't go out of range and manually update your buffer.

Matt Breckon
I don't think this is what is meant by the question.
driis
Actually this is definitely the best answer so far.
Ronnie Overby
Throw this into an Extension method so you could call Console.ReadLine("135"); Can Extension methods be overloads of existing methods? If not, give it a new name.
Dennis Palmer
@Dennis - You can't add extension methods to static classes because you can't create instances of them. Maybe SuperConsole.ReadLine("default")? There are a lot of cases to handle, but coding this out and packaging it into a DLL should be worth it.
Ronnie Overby
Dennis Palmer