Home > Software design >  how can i accept "null" word in my integer value? its like if i enter the word "null&
how can i accept "null" word in my integer value? its like if i enter the word "null&

Time:02-20

        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:

CodePudding user response:

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: ");
}

CodePudding user response:

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();
        }
  •  Tags:  
  • c#
  • Related