Take the 2-minute tour ×

I have this:

List<object> nodes = new List<object>(); 

new {
    Checked		= false,
    depth		= 1,
    id			= "div_" + d.Id

... and I'm wondering if I can then grab the "Checked" property of the anonymous object. I'm not sure if this is even possible. Tried doing this:

if (nodes.Any(n => n["Checked"] == false)) ... but it doesn't work.


share|improve this question
add comment

3 Answers

up vote 34 down vote accepted

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });
share|improve this answer
add comment

If you're storing the object as type object, you need to use reflection. This is true of any object type, anonymous or otherwise. On an object o, you can get its type:

Type t = o.GetType();

Then from that you look up a property:

PropertyInfo p = t.GetProperty("Foo");

Then from that you can get a value:

object v = p.GetValue(o, null);

This answer is long overdue for an update for C# 4:

dynamic d = o;
object v = d.Foo;
share|improve this answer
Never used a dynamic before till now, nice update for .NET 4.0 –  Alan Nov 9 '12 at 17:10
woow, good for C#4 =D this work for me –  ch2o Jan 16 '13 at 16:24
add comment

You could iterate over the anonymous type's properties using Reflection; see if there is a "Checked" property and if there is then get its value.

See this blog post: http://blogs.msdn.com/wriju/archive/2007/10/26/c-3-0-anonymous-type-and-net-reflection-hand-in-hand.aspx

So something like:

foreach(object o in nodes)
    Type t = o.GetType();

    PropertyInfo[] pi = t.GetProperties(); 

    foreach (PropertyInfo p in pi)
        if (p.Name=="Checked" && !o.GetValue("Checked"))
share|improve this answer
If you only need one property and you already know its name, there's no point in going through all of them; just use GetProperty and GetValue. Also, System.out.println is Java, not C#... –  Chris Charabaruk Jan 10 '11 at 1:40
Oops, so it is, Chris! A bit embarrassing...fixed now. –  glennkentwell Jan 10 '11 at 4:55
add comment

Your Answer


