I'm learning C# (VS 2012 Professional) and in the following example, the console window isn't staying open even though the Console.ReadLine()
method is the last instruction in the code block:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testing
{
class Program
{
static void Main(string[] args)
{
// fahrenheit conversion example
Console.Write("Enter temp in fahrenheit: ");
double fahrenheit = Console.Read();
double celsius = (fahrenheit - 32.0) * (5.0 / 9.0);
Console.WriteLine("Celsius is: " + celsius);
Console.ReadLine();
}
}
}
Is there an intricacy I am overlooking in the implementation of the Console.ReadLine()
method or perhaps a conflicting piece of code in the code block?
Probably you type the value for the fahrenheit
variable and then press Return (Enter).
This will get the value in the Read call and the Enter in the ReadLine.
Change to
Console.Write("Enter temp in fahrenheit: ");
double fahrenheit;
string userInput = Console.ReadLine();
if(double.TryParse(userInput, out fahrenheit))
{
double celsius = (fahrenheit - 32.0) * (5.0 / 9.0);
Console.WriteLine("Celsius is: " + celsius);
}
else
{
Console.WriteLine("Non a valid double value");
}
Console.ReadLine();
Also, the Console.ReadLine, unlike the Console.Read, returns a string and thus you need to parse and convert to a double before trying to use it. This could be done with double.TryParse that will return false when the user doesn't type a valid numeric double
Another drawback for Console.Read is that you need to call it in a loop to read all characters typed by the user till the Enter. If you try to convert 12.8 you need a completely different code to go with Console.Read. (Look at the MSDN example in the link above)