开发者

var item throwing exception when tested against null

开发者 https://www.devze.com 2023-04-06 13:17 出处:网络
I am seeing some strange behaviour testing for null value against a var type using C#.NET Here is some sample code.

I am seeing some strange behaviour testing for null value against a var type using C#.NET

Here is some sample code.

//  locate user in cache

var user = GWUsers.Instance.Users.Where(u => u.EmailAddress == emailAddress).FirstOrDefault();

if (user != null)
{

} 

When the user contains a null value an exception is thrown indicating that the "object reference is not set".

GWUsers is a singleton used to hold a list of users stored in an XML file. This very same piece of code is used throughout the application, but in this one instance, it throws an exception when evaluated against a null.

Any ide开发者_如何学JAVAas why that might be?

Appreciate any insight on this.

Thanks


Very likely the following could be the reasons:

  • GWUsers.Instance.Users is null
  • One of the instances in the list is null


In the case of a null user element within Users, you could modify the LINQ statement to the following:

GWUsers.Instance.Users.Where(u => u != null && u.EmailAddress == u.mailAddress).FirstOrDefault();`

It would not help with Users being null, however.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号