Search code examples
c#defaultoption-type

C# Pass an integer variable with an optional default value


class Program
{
    static void Main(string[] args)
    {
        WriteLine("What is the radius of your circle: ");
        WriteLine("The area of your circle is: " + 
            circleArea(Double.Parse(ReadLine())).ToString());
        ReadKey();
    }

    static double circleArea(double radius = 5.00)
    {            
        return Math.PI * (radius * radius);
    }
}

I thought I had it set up correctly; however, I receive an error of System.FormatException: 'Input string was not in a correct format. on the line WriteLine("The area of your circle is: " + circleArea(Double.Parse(ReadLine())).ToString()); when no value is entered. I would like it to have a default value of 2. Thanks.


Solution

  • Your problem is that you need to split out the conversion to be able to test for a bad input condition. Take a look at this code.

                Console.WriteLine("What is the radius of your circle: ");
            var isNumber = Double.TryParse(Console.ReadLine(), out double number);
            if (!isNumber)
                number = 0;
            Console.WriteLine("The area of your circle is: " + circleArea(number).ToString());
            Console.ReadKey();
    

    This will test for a legitimate number and if it's not, it just passes zero as the number.