Xml to Linq where clause and "Possible System.NullReferenceException"
Often I write a Linq query like the following:
from el in _data.Descendants("elements")
where el.Attribute("myattr") != null && el.Attribute("myattr").Value == someValue
select el
Resharper always gives a "possible null reference" warning for the second el.Attribute("myattr") reference. I can understand why this warning is given but I can't work out a clean way of rewriting the code to get rid of the warning.
Any ideas?
Please sign in to leave a comment.
Hello JorgeBurgos,
Does it help you to rewrite it as follows?
from el in _data.Descendants("elements")
let attr = el.Attribute("myattr")
where attr != null && attr.Value == someValue
select el
Sincerely,
Ilya Ryzhenkov
JetBrains, Inc
http://www.jetbrains.com
"Develop with pleasure!"
J> Often I write a Linq query like the following:
J>
J> from el in _data.Descendants("elements")
where
J> el.Attribute("myattr") != null && el.Attribute("myattr").Value ==
J> someValue
J>
J> select el
J>
J> Resharper always gives a "possible null reference" warning for the
J> second el.Attribute("myattr") reference. I can understand why this
J> warning is given but I can't work out a clean way of rewriting the
J> code to get rid of the warning.
J>
J> Any ideas?
J>
J> ---
J> Original message URL:
J> http://www.jetbrains.net/devnet/message/5228486#5228486
Great thanks, that's the type of refactoring I was looking for!
If, in your example, I would leave out the null check
ReSharper (6.1) doesn't warn anymore about a possible NullReferenceException, even thoug it can still appear. Is this a bug?