views:

133

answers:

2

I recently wrote a piece of code that looked a bit like this:

IEnumerable<DTO.Employee> xEmployee =
    from e in xDoc.Descendants("Employee")
    where int.Parse(e.Attribute("Id").Value) == emp.Id
    select new DTO.Employee
    {
        Id = (int)e.Attribute("Id"),
        LastName = (string)e.Element("LastName"),
        FirstName = (string)e.Element("FirstName"),
        Email = (string)e.Element("Email")
    };

However, I am confused about the casting to an int in the where clause. First, I'd written something like

where (int)(e.Attribute("Id").Value) == emp.Id

which didn't compile. Why can I do a explicit cast on (e.Attribute("Id")), but can 't I do this on (e.Attribute("Id").Value)?

+2  A: 

Check out the explicit operator overloads of the XAttribute class.

public static explicit operator int(XAttribute attribute);
ChaosPandion
+1  A: 

There is an explicit conversion from XAttribute to int - but there's no explicit conversion from string (the type of XAttribute.Value) to int.

Jon Skeet