Search code examples
c#expando

How to get invoking member name of expando object?


dynamic test = new ExpandoObject();
test.A = "ok";

try{
    Console.WriteLine(test.B);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex){
    // how can i know that B was invoke?
}

As code above, test.B is not a member of 'test'. But how can i know 'B' is calling. The only way i found is looking into ex.Message but it's not a proper way.


Solution

  • It will be easier if you use DynamicObject instead of ExpandoObject.

    class MyDynamicObject : DynamicObject
    {
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            Console.WriteLine(binder.Name);
             //simply prints the name, you can raise an event here or something else
            return base.TryGetMember(binder, out result);
        }
    }