Resolved warning CS8602: Dereference of a possibly null reference.

cbreemer

Well-known member
Joined
Dec 1, 2021
Messages
191
Programming Experience
10+
I'm a bit puzzled by this compiler warning, which I get on this line in my DataGridView program:

if (grid.Rows.Cells[COLUMN_FILE].Value.ToString().ToUpper().StartsWith(jumper))

I think the message pertains to the member Value being potentially null. Although I'm not quite sure because of the way the IDE places the squiggly line:

a.jpg

suggesting the issue is with the ToString() method?
Anyway I honestly don't understand why the compiler needs to fuss over something like this. In the unlikely event that I forgot to fill a grid cell, I would be more than happy to get a runtime exception.
But putting it in a try\catch does not get rid of the error, nor does explicitly testing for null.
It's not a problem, I can choose to ignore or suppress the warning, but I don't like either of these options.
I want this to compile cleanly but can't figure out how. I vaguely remember something called GetValueOrDefault() but I could not make that work here.
Also I can't decide whether the compiler is helpful or pedantic (and is there even a difference in a case like this).

Any ideas?
 

Attachments

  • a.jpg
    a.jpg
    86.5 KB · Views: 5
Last edited:
Thanks for that @JohnH. Somehow I was firmly convinced that toString() would always return a value regardless of the object. At least this restores my faith in the squiggly lines.
Adding the null-forgiving operator fixes the warning. But I found I could fix it in the following (naïve but more descriptive) way

var val = (string)grid.Rows.Cells[COLUMN_FILE].Value;
if (val.ToString().ToUpper().StartsWith(jumper))


I had not expected to get away with this though :D
 
Instead of ToUpper().StartsWith that create an extra string, it is recommended to use case-insensitive comparison, either CurrentCultureIgnoreCase or InvariantCultureIgnoreCase.
C#:
if (val.StartsWith(jumper, StringComparison.CurrentCultureIgnoreCase)) { }
 
Instead of ToUpper().StartsWith that create an extra string, it is recommended to use case-insensitive comparison, either CurrentCultureIgnoreCase or InvariantCultureIgnoreCase.
C#:
if (val.StartsWith(jumper, StringComparison.CurrentCultureIgnoreCase)) { }

Yes, that is the smarter way to go. I used toUpper() because the jumper string is always in uppercase 😁
Man y thanks for your help. I'll mark it solved now.
 
Back
Top Bottom