I am passing a handler function as an argument to another function. One of the arguments of the handler is a dynamic object and I am accessing one of its properties.
Here is an example:
protected virtual void OnTime(dynamic timed, HttpResponseMessage response, TimeSpan time)
{
_logger.Write(timed?.name);
}
And here is how the handler gets invoked:
OnTime?.Invoke(new {name = dto.name, dto, request }, httpResponseMessage, elapsed);
This worked well. Then I shuffled some things around and it broke. The dynamic object comes in as expected with all of its properties but now timed?.name throws Microsoft.CSharp.RuntimeBinder.RuntimeBinderException exception complaining that the object does not have a definition of property name.
I looked at these answers for a solution:
Why does the assignment from a dynamic object throw a RuntimeBinderException?
Dynamic throwing Microsoft.CSharp.RuntimeBinder.RuntimeBinderException on private types
and the following works:
Dictionary<string, object> values = ((object)timed)
.GetType()
.GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(v));
(Get properties of a Dynamic Type)
but I am not sure why direct access stopped working. Any ideas? Thank you!