Home > Back-end >  C#: null warning even though it's not possible
C#: null warning even though it's not possible

Time:06-03

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
} 

CodePudding user response:

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
} 
  • Related