Linq: comparison with nonexisting value should not cause the exception, but it does

Posted by Seacat on Stack Overflow See other posts from Stack Overflow or by Seacat
Published on 2011-01-11T02:42:55Z Indexed on 2011/01/11 2:54 UTC
Read the original article Hit count: 190

Filed under:
|

Hello, Given I don't know if the parameter will be null or not and I want to use it in the following way: if Param != null then compare with its id if Param == null then compare with null.

Something like that:

var c = from cat in context.Categories
where ParamCat != null && cat.ParentId == ParamCat.Id 
||
ParamCat == null && cat.ParentId == null
select c;

If ParamCat is null as soon as I try to get something from c (for example c.Count()) it throws the exception.

Usually when we use some kind of condition it stop comparison as soon as condition fail especially if we use AND. For example this code will not cause any exception:

if (ParamCat != null &&  cat.ParentId == RaramCat.Id)
{
}

If so, why the linq code above throw exception? (Null reference)

Thanks

© Stack Overflow or respective owner

Related posts about .NET

Related posts about LINQ