I have a method that continuously gives me a warning "is not null here".
StockHolding stockHoldingFiltered = new StockHolding();
List<StockHolding> stockHoldingsFiltered = new List<StockHolding>();
IReadOnlyList<StockHolding> stockHoldings = this.GetAll();
stockHoldingsFiltered = stockHoldings.Where(stckhold =>
stckhold.PortfolioId.Equals(portfolioId) &&
stckhold.StockSymbol.Equals(stockSymbol)).ToList();
if(stockHoldingsFiltered != null)
stockHoldingFiltered = stockHoldingsFiltered.FirstOrDefault();
return stockHoldingFiltered;
Warning: 'stockHoldingFiltered' is not null here. CS8600: Converting null literal or possible null value to non-nullable type.
I cannot get this warning to go away. Has anyone run into this and were able to resolve this warning?
CodePudding user response:
This issue is with your if statement. You are doing a null check on a ToList()
. The list isn't going to be null, but it can however be empty. Here is your code below to demonstrate this.
void Main()
{
int portfolioId = 1;
string stockSymbol = "USD";
StockHolding stockHoldingFiltered = new StockHolding();
List<StockHolding> stockHoldingsFiltered = new List<StockHolding>();
IReadOnlyList<StockHolding> stockHoldings = StockHolding.GetAll();
stockHoldingsFiltered = stockHoldings.Where(stckhold =>
stckhold.PortfolioId.Equals(portfolioId) &&
stckhold.StockSymbol.Equals(stockSymbol)).ToList();
if (stockHoldingsFiltered != null) // this cannot be null as its returning a list. It might be empty but not null.
{
Console.WriteLine("I WASN't NULL, but has no records. Line below will fail.");
//stockHoldingFiltered = stockHoldingsFiltered.FirstOrDefault();
}
if(stockHoldingsFiltered.Count > 0)
{
Console.WriteLine("I wasnt null but had 0 records. Line below is safe");
stockHoldingFiltered = stockHoldingsFiltered.FirstOrDefault();
}
//return stockHoldingFiltered;
}
// You can define other methods, fields, classes and namespaces here
public class StockHolding
{
public int PortfolioId { get; set; }
public string StockSymbol { get; set; }
public static IReadOnlyList<StockHolding> GetAll()
{
List<StockHolding> someList = new List<StockHolding>();
return someList;
}
}
This outputs: I WASN't NULL, but has no records. Line below will fail.
So instead of if (stockHoldingsFiltered != null)
try using if(stockHoldingsFiltered.Count > 0)
That warning will go away.