I have a simple C# statement:
var code = container.thing.result.decode ?? "Unknown";
That throws an “Object reference not set to an instance of an object.” exception when the database value is null. It works perfectly (so far) with non-null values. I tried being more explicit and rewrote the line with a ternary operator:
var outcome = container.thing.result.decode == null ? "Unknown" : container.thing.result.decode;
And I get the same result with the same exception (and ReSharper guides me back to the much simpler ?? statement).
I also read that the ?? operator only works with nullable types. The field I’m working with is not a nullable type, it’s an nvarchar(100) and also a foreign key to a lookup table. As I said above, the statement works with a valid non-null value.
The application’s ORM also has a CODE value, to make a CODE and DECODE pair, which looks like it maps to the lookup table as it should.
But I can’t figure out how to deal with null values.
Thank you!
EDIT: Thank you for the quick responses! I did figure out where I was confused only minutes after posting. I think writing the question out helped me delineate the problem. I changed the statement to check if the actual field referencing the lookup table is null:
var outcome = container.thing.database_code_field == null ? "Unknown" : container.thing.result.Decode;
This looks like what I want. Thank you again!
You’ll get an exception if any of the following is null:
containercontainer.thingcontainer.thing.resultWe can’t tell which of those values is null in your situation, or whether null is a valid value. You should work that out and then either fix whatever’s giving you a null value, or write code to handle that case.