So, this is the first time I'm immersed in Linq in XML (I know that I'm behind), and so far it's pretty cool. However, I came across this very confusing behavior.
I am parsing the common .resx format. It has data tags that have value and optional comment . Here is the code I tried first:
var items = from str in doc.Root.Descendants("data") select new ResourceValue { Name = str.Attribute("name").Value, Value = str.Element("value").Value, Comment=str.Element("comment").Value };
Of course, when I get the .value element of the comment element, but it throws an exception with an empty link. Well, try again. I heard that you can overlay an XElement on a string and it will magically work. Let's try to
var items = from str in doc.Root.Descendants("data") select new ResourceValue { Name = str.Attribute("name").Value, Value = str.Element("value").Value, Comment=str.Element("comment") as string };
Ohhhh. This time I get a compiler error.
It is not possible to convert the type 'System.Xml.Linq.XElement' to 'string' through link conversion, box conversion, decompression conversion, packaging conversion, or null type conversion
Well, this is strange .. Let the search stackoverflow. And so, I find a snippet that offers this instead:
var items = from str in doc.Root.Descendants("data") select new ResourceValue { Name = str.Attribute("name").Value, Value = str.Element("value").Value, Comment=(string)str.Element("comment") };
Wow. It works!? But, casting null to a string throws a link reference exception ... right? I thought that as string was exactly for this situation !?
How does it work and why can I make an explicit cast, but not an explicit expression of as ?