Home > Software engineering >  Is it okay warnings in c# or should I do something?
Is it okay warnings in c# or should I do something?

Time:12-11

My code works properly but every time when i run the code I have warning which I can not understand. I run the code in my linux terminal it says: Converting null literal or possible null value to non-nullable type Is it normal? Or should I do something? Here is my code:

namespace test2;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Choose option: \n1.  \n2. -\n3. *\n4. /");
        int num = Convert.ToInt32(Console.ReadLine());
        string ext = Console.ReadLine();
        if(num == 1){
            while(true){
                Console.WriteLine("Enter numbers or tap Q to exit:");
            int x = Convert.ToInt32(Console.ReadLine());
            int y = Convert.ToInt32(Console.ReadLine());
            int z = x   y;
            Console.WriteLine("{0} {1}={2}", x,y,z);
            if(ext =="Q"){
                break;
            }
        }
        }
    }
}

I tried to write ext inside while loop but I can't

CodePudding user response:

The warning is to tell you that the right side expression could return a null value and in your case, the left side of the variable is not nullable.

Refer the declaration of Console.ReadLine, it returns string?.

so you can declare it like string? ext = Console.ReadLine(); to get rid of this warning.

CodePudding user response:

Try replacing Convert.ToInt32 with int.Parse

CodePudding user response:

The warning is related to assigning a nullable type to nun-nullable type. A simple alternative is to use int.tryparse() method like this:

int num;
int.TryParse(Console.ReadLine(),out num);

CodePudding user response:

You can define a variable with a null default like

int? num = Convert.ToInt32(Console.ReadLine());
  • Related