How to set default input value in .Net Console App

2019-01-20 07:47发布

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.

7条回答
老娘就宠你
2楼-- · 2019-01-20 08:41

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;
查看更多
登录 后发表回答