In this tutorial example we will use the console application with .NET core. Now let's check the below code.
Validate Inter String
string intValue = "2312";
bool isnumber = int.TryParse(intValue, out int number);
if (isnumber)
{
Console.WriteLine("This is a number and number is "+number);
}
else
{
Console.WriteLine("Error: Not a number");
}
In above code I have defined a string variable. To validate a string value is a number or not by using int.TryParse. Here one thing you need to check out int number. This will provide the number which we have passed. It act as an output parameter. Now you you dont want any value to return just to validate you ca pass "_" as shown below.bool isnumber = int.TryParse(intValue, out _);
Now let's run the code to check the output.
Now let's check the other part, by passing a string value not a number in the same code.
Validate Decimal String
We have already seen that to validate the pass string is an integer or not. Now in this code example we will validate the pass string is a decimal value or not. Please refer the below code.
string decimalValue = "12.5";
bool isnumber = decimal.TryParse(decimalValue, out decimal number);
if (isnumber)
{
Console.WriteLine("This is a decimal number and number is " + number);
}
else
{
Console.WriteLine("Error: Not a decimal number");
}
In above code i have string a variable in which I have passed a string value "12.5". Now we will validate whether this string decimal value is a decimal value or not. Now lets run the code to check the output.Now let's change the value and check the output.