Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In C#, although the variable is null in the code, it does not enter the else block

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);
        }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading