1

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?

rofans91
  • 2,970
  • 11
  • 45
  • 60
Daan
  • 1,417
  • 5
  • 25
  • 40
  • possible duplicate of [Accessing C# Anonymous Type Objects](http://stackoverflow.com/questions/713521/accessing-c-sharp-anonymous-type-objects) – nawfal Jun 28 '14 at 08:55

2 Answers2

2

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.

Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158
1

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.

Community
  • 1
  • 1
Kai G
  • 3,371
  • 3
  • 26
  • 30