1

errorMy goal in this program is to allow the user to change the values in a operation and find the area(basically useless calculator) of the rectangle. The results i would expect(from python exp.) is that is woulld read the line and convert it into int, then i could multiply the two variables to get the area. Whenever I have tried this, the Error CS8600('Converting null literal to non-nullable type') in line 10(string name = Console.ReadLine();) I first thought that it could be some problem with the conversion to integer(Spare me, i am very new to this language and Object Oriented Programming in general.) I have not found solutions that i can understand online and am resorting to Stack Overflow. Here's the code, please help me:


namespace world
{
    class Username
    {
        static void Main(string[] args)/* by accident i wrote public*/
        {
            Console.WriteLine("What is your name? ");
            string name = Console.ReadLine();
            Console.WriteLine("Your name is " + name);
            Console.WriteLine("Now about rectangles...");
            Console.WriteLine("Length = ");
            string inlength = Console.ReadLine()??string.Empty;
            int length;
            Int32.TryParse(inlength, out length);
            Console.WriteLine("Width = ");
            string inwidth = Console.ReadLine()??string.Empty;
            int width;
            Int32.TryParse(inwidth, out width);
            int area = length * width;
            Console.WriteLine(area);


        }
    }
}
JebKerman
  • 23
  • 6

1 Answers1

2
  • null in C# is similar (though far from identical) to null in other languages like JavaScript or None in Python.
  • Your string name statement declares a variable named name of type non-nullable System.String
    • The string keyword in C# is an alias for the System.String type.
  • However, the Console.ReadLine() method has a return-type of nullable System.String (i.e. string?).
  • Therefore, you need to consider how your program will behave in the event the user presses Ctrl + Z while at the "What is your name?" prompt.
  • The quick-fix is to disregard Ctrl + Z input and treat it the same as empty-input, in which case the use of ?? String.Empty (or just ?? "") is perfectly fine, and is what you're already doing in the rest of your program already.
Dai
  • 141,631
  • 28
  • 261
  • 374