Do not use the class Convert
if you try to parse a text that has been entered by the user because it is possible that the text is not a valid value of the type of data you want to obtain. Instead it uses the TryParse()
method of the target data type.
Example with the case of Single
(in C # alias float
)
C # 7 or higher
if (Single.TryParse(Console.ReadLine(), out float numero))
{
// Acá la variable numero tiene el valor asignado
}
else
{
// No se pudo converir el dato ingresado por el usuario en float
}
C # 6 or lower
float result;
if (Single.TryParse(Console.ReadLine(), out numero))
{
// Acá la variable numero tiene el valor asignado
}
else
{
// No se pudo converir el dato ingresado por el usuario en float
}
The same can be done in the case of decimal
and double
, the 3 types of data have the method TryParse()