How to access property of anonymous type in C#?

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;

And now another alternative in C# 6:

object v = o?.GetType().GetProperty("Foo")?.GetValue(o, null);

Note that by using ?. we cause the resulting v to be null in three different situations!

  1. o is null, so there is no object at all
  2. o is non-null but doesn’t have a property Foo
  3. o has a property Foo but its real value happens to be null.

So this is not equivalent to the earlier examples, but may make sense if you want to treat all three cases the same.

To use dynamic to read properties of anonymous type in your Unit Tests, You need to tell your project’s compiler services to make the assembly visible internally to your test project. You can add the following into your the project (.proj) file. Refer this link for more information.

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
        <_Parameter1>Name of your test project</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

Leave a Comment