'how can i accept "null" word in my integer value? its like if i enter the word "null" the output would be empty. like, Enter your age: null, Your age:
int? age;
Console.Write("\nInsert age: ");
age = Convert.ToInt32(Console.ReadLine());
if (age == null)
{
Console.WriteLine("Your age:" + age);
}
else
{
Console.WriteLine("Your age: ");
}
It works correctly if i put integer but every time i put the word "null" it always appears "exception unhandle". Anyone there who can help me out
The program output should be this:
Insert Age:12
Your age:12
Insert Age:null
Your age:
Solution 1:[1]
I would sugest to use a convert method which does not throw a exception like TryParse. This method returns a bool to check if the input string contained a valid integer:
bool validNumber = int.TryParse(Console.ReadLine(), out var age);
if (validNumber)
{
Console.WriteLine($"Your age: {age}");
}
else
{
Console.WriteLine($"Your age: ");
}
Solution 2:[2]
You cannot store string values in int datatype. Below code achieves your expected outcome. In string variable age - you can store both - age number in string format and null value.
string age;
Console.Write("\nInsert age: ");
age = Console.ReadLine();
if (age.Equals("null"))
{
Console.WriteLine("Your age:"+"");
Console.ReadLine();
}
else
{
Console.WriteLine("Your age:"+age);
Console.ReadLine();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jannik |
| Solution 2 |
