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

C#: null warning even though it's not possible

Ok so here I have this function that can return a null value in some cases. However, even when testing if it is before, it still says it might be null.

My code:

if (Account.FindAccount(usernameInput) == null) { return; }    
if (Account.FindAccount(usernameInput).password == "1234") // warning CS8602: Dereference of a possibly null reference
{ 
    //Do stuff
} 

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

>Solution :

Is that FindAccount operation guaranteed to be idempotent? The compiler has no such guarantee. What it returns in one call it might not return in another.

More to the point… If you believe it will always return the same result for the same input, why are you invoking it twice? Just invoke it once and store the result:

var account = Account.FindAccount(usernameInput);
if (account == null) { return; }    
if (account.password == "1234")
{ 
    //Do stuff
} 
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