How to make a validation in C #?

2

I'm new to this C # and my question is: how can I do a number validation for a calculator?

I would like to apply the validation in this part of my code:

float a, b;
Console.Write("INGRESE PRIMER VALOR: ");
a = float.Parse(Console.ReadLine());
Console.Write("INGRESE SEGUNDO VALOR: ");
b = float.Parse(Console.ReadLine());

Many thanks in advance!

    
asked by RicardoCarlos de la Rosa 27.06.2017 в 05:39
source

1 answer

4

Instead of using Parse, you should use TryParse that returns a bool to know if it is valid or not, which if you combine it with a while loop, would be as follows:

using System.Globalization;//libreria a añadir para usar las funcionalidades que mas abajo se menciona.

float a;
float outVariable;
Console.Write("INGRESE PRIMER VALOR: ");
while(!float.TryParse(Console.ReadLine(),
                      NumberStyles.Float | NumberStyles.AllowThousands,
                      CultureInfo.InvariantCulture,
                      out outVariable))
{
   Console.Write("INGRESE PRIMER VALOR: ");
}//fin del ciclo while

   Console.ReadKey();

Greetings

    
answered by 27.06.2017 / 06:02
source