I came across this problem but have been unable to figure out what is causing it and have been unable to replicate it, despite my attempts here https://dotnetfiddle.net/xDVa2a. My classes are structured like so:
public abstract class ProductNode
{
public ProductCategory ParentCategory { get; set; }
}
public class ProductCategory : ProductNode { }
public class TreeNode<T> where T : class
{
private readonly T _value;
public T Value() {
return _value;
}
public TreeNode(T value) {
_value = value;
}
}
In my code I create a TreeNode of type ProductNode with the constructor argument as null and use LINQ to filter an IQueryable to compare the ProductNode against the value in the TreeNode.
IQueryable<ProductNode> allProductNodes = _context.ProductNodes;
TreeNode<ProductNode> treeNode = new TreeNode<ProductNode>(null);
List<ProductNode> productNodes = allProductNodes
.Where(node => node.ParentCategory == treeNode.Value()).ToList(); // NullReferenceException
This throws a NullReferenceException, however if I tweak my query to compare against null it works.
List<ProductNode> productNodes = allProductNodes
.Where(node => node.ParentCategory == null).ToList(); // Works
List<ProductNode> productNodes = allProductNodes
.Where(node => node.ParentCategory == (treeNode.Value() ?? null)).ToList(); // Alternative, working solution
What is causing the compiler to throw the exception?