markjprice / cs10dotnet6

Repository for the Packt Publishing book titled "C# 10 and .NET 6 - Modern Cross-Platform Development" by Mark J. Price
858 stars 375 forks source link

Chap 06: Comparing objects #93

Open Strydir opened 2 years ago

Strydir commented 2 years ago

Page 235: the line "int result = x.Name.Length.CompareTo(y.Name.Length) results in the errors "'Name may be null here. Dereference of a possibly null reference".

To fix it, you must test to make sure that Name is not null first:

if((x is not null) && (y is not null)) { if(x.Name is null) return 1; if(y.Name is null) return -1; int result = x.Name.Length.CompareTo(y.Name.Length); }

Obviously, the errors disappear if you modify the file according to the "errata" for null values for page 235, but, as printed, the text does not work. A possible VS Code version issue? Using VS Code version 1.69.1

markjprice commented 2 years ago

It's nothing to do with Visual Studio Code. It is a mistake in the printed book. The Person class has a Name property defined as a nullable string but that statement does not check for null. That's why the errata exists to fix that, as well as improve null handling in other ways too.

Strydir commented 2 years ago

Well, it's not IN the errata, so I thought that I'd bring it to your attention. If you are planning on adding it, then great. I find your response rather rude.
You're welcome for bringing it to your attention.

markjprice commented 2 years ago

Sorry! It was not my intention to be rude. The errata as it exists both fixes the issue and improves the code example, so there is nothing to add. That's all I meant.

Strydir commented 2 years ago

Well, as a user, I went to your errata page specifically to find out why that page does not work and I find absolutely NO reference to the fact that there is an error in the book. I almost pitched the book (means to throw it in the garbage) because the book is apparently wrong but there is no reference to the error. Please add a note stating that there is an error on the page so that dumb people like me don't spend so much freaking TIME trying to determine if I'M missing something!
Wow!