How to set default input value in .Net Console App?

前端 未结 8 1418
时光取名叫无心
时光取名叫无心 2020-12-11 16:01

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 inp         


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 16: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;
    

提交回复
热议问题