2

I'm using FastMember for an alternative to reflection. In the source, I see there is a unit test for anonymous type support, but I'm getting a NotSupportedException when I attempt to TypeMember.CreateNew() for an anonymous type. Are they not supported?

kapex
  • 28,903
  • 6
  • 107
  • 121
pianomanjh
  • 233
  • 1
  • 14

2 Answers2

0

They are supported but not with TypeMember - you should be using ObjectAccessor instead like:

var obj = new {A = 123, B = "def"};
var accessor = ObjectAccessor.Create(obj);
Assert.AreEqual(123, accessor["A"]);
Wolfwyrd
  • 15,716
  • 5
  • 47
  • 67
  • Anonymous types are generated at compile-time, therefore I don't think they belong to the DLR and that's why you can use `TypeAccessor` instead of `ObjectAccessor` – Phate01 May 09 '23 at 16:03
0

Very old question but I just had the same doubt and you can simply do:

var anon = new
{
    Prop1 = "a",
    Prop2 = "b"
};

MemberSet members =
    TypeAccessor
        .Create(anon.GetType())
        .GetMembers();
Phate01
  • 2,499
  • 2
  • 30
  • 55