C# – How to get a value of a property from an anonymous type


I have a datagrid populated by a Linq query. When the focused row in the datagrid changes I need to set a variable equal to one of the properties in that object.

I tried…

var selectedObject = view.GetRow(rowHandle);
_selectedId = selectedObject.Id;

… but the compiler doesn't care for this at all ("Embedded statement cannot be a declaration or labled statement").

It seems like the property should be easy to access. Inspecting the object during runtime shows all the properties I expect, I just don't know how to access them.

How can I get access to the anonymous object's property?

Edit for Clarifications:

I happen to be using DevExpress XtraGrid control. I loaded this control with a Linq query which was composed of several different objects, therefore making the data not really conforming with any one class I already have (ie, I cannot cast this to anything).

I'm using .NET 3.5.

When I view the results of the view.GetRow(rowHandle) method I get an anonymous type that looks like this:

{ ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 }

My objective is to get the ClientId from this anonymous type so I can do other things (such as a load a form with that client record in it).

I tried a couple of the suggestions in the early answers but was unable to get to a point where I could get this ClientId.

Best Answer

Have you ever tried to use reflection? Here's a sample code snippet:

// use reflection to retrieve the values of the following anonymous type
var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 }; 
System.Type type = obj.GetType(); 
int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);

// use the retrieved values for whatever you want...