0

When my Database.defaultCard list is empty, it sends null into FirstOrDefault done (I know so). But when sending null value, it doesn't enter else block and An unhandled exception of type 'System.NullReferenceException' occurred in ToDo_App.dll: 'Object reference not set to an instance of an object.' I get an error. No matter what I did, it didn't go into the else block. How can I solve this or if there is something I need to know, can you write?

       string done = Database.defaultCard.FirstOrDefault(x => x.Line == "DONE").Line;
        if (done!=null)
        {
            ListingProgressNotNull(done);
        }
        else
        {
            done = "DONE";
            ListingProgressNull(done);
        }
Manly
  • 61
  • 6
  • You need to check if `Database.defaultCard` is null and do an appropriate action. You cannot call `FirstOrDefault` on `null`. – Palle Due Dec 23 '22 at 12:41
  • @PalleDue No the issue is that `FirstOrDefault` returns null and they try to deference that to get `Line`. – juharr Dec 23 '22 at 13:14

1 Answers1

2

If FirstOrDefault returns nullyou are still trying to access the property Line. This causes the null exception.

Use the null conditional operator: ?.

string done = Database.defaultCard.FirstOrDefault(x => x.Line == "DONE")?.Line;

If defaultcard can be null use it also there:

string done = Database.defaultCard?.FirstOrDefault(x => x.Line == "DONE")?.Line;

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
schgab
  • 521
  • 5
  • 19