Daan
Daan

Reputation: 1437

Writing to XML with anonymous types?

Right now, I'm reading an XML document and pass its main elements to the method below. This method then returns the relevant elements in a IEnumerable, which is used to update a DataGridView.

private IEnumerable<object> readRelease(IEnumerable<XElement> release)
{
    return (
        from r in release
        select new
        {
            Release = r.Attribute("id").Value
            //etc.
        });
}

For the DataGridView, this method works well, but what if I want to write these elements to an XML file or, more broadly, just want to access a particular variable (e.g. "Release"). Can I then still use this method or should I go for something else?

Upvotes: 1

Views: 177

Answers (2)

Andrew Savinykh
Andrew Savinykh

Reputation: 26270

Kai is correct, however I'd like to point out that another option would be to use dynamic instead of object if your c# compiler supports it. Then you can access properties and these will be resolved at the run-time. But as mentioned, in your scenario you most likely will be better off defining a new type.

Upvotes: 2

Kai G
Kai G

Reputation: 3492

There's another SO question about a dirty hack that allows you to access anonymous types outside a method but nobody would recommend using it:

Accessing C# Anonymous Type Objects

If you need to access particular variables outside of the method it would probably be a better idea to define a new type instead of using an anonymous one.

Upvotes: 1

Related Questions