Console.Read says it reads the next character from input. If you set a debugger at your if, and see what value you get, you’ll see num is set to 54 which is ‘6’ in ASCII.
54 is even thus your result.
Console.ReadLine will read all the characters you type until you press enter. It will be a string and you will have to convert to int.
Your first troubleshooting step should be to print ‘num’ to the console to see what its value is (a more advanced method would be to use a breakpoint and inspect it in the debugger).
This would tell you that Console.Read doesn’t return the value you expect; looking at the documentation, either by googling ‘C# Console.Read’ or the tool tip popup in Visual Studio would show that Console.Read returns:
Thus if you type 65 you get ’54’ which is the ASCII value of ‘6’ cast to an int.
Long story short what you are looking for is
VS also launch either the Help Viewer or MSDN website to the appropriate topic if F1 is pressed when the cursor is on the “.Read” part.
I will explain the answer in the below parts of my comment here, but you should try debugging it first. Try printing the number you read in from console, because it isn’t going to be what you think it is.
After you’ve printed the number you typed in, take a look at what exactly the Console.Read()
method returns. It DOES return an int, but it does NOT return the number the user typed in. You can read the docs here: https://docs.microsoft.com/en-us/dotnet/api/system.console.read?view=net-5.0
That page has an example of correctly printing what the user typed in, but the short answer is that number returned by Console.Read()
is in ASCII, and as the documentation says, it reads one character at a time. So if you type in “65” then this code will read in the character “6” first, which in ascii is integer 54. You can verify this by looking at an ascii table such as here http://www.asciitable.com/.
And so since num
is 54, which is divisible by 2, this is why your code prints that its dividable.
You should definitely look into how to set and use breakpoints. Do it now, because it’s something that you will use your whole developer life.
Anyway, as others have said, if you debug the value of “num” you will see it is not 65, but 54. The reasons for this have been explained by others.
Here’s a screenshot to show you my debugging.
C# devs
null reference exceptions