Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Object - How to tell if a property is defined?

Tags:

c#

dynamic

I have a dynamic object that looks as follows:

this.ChartDetails.Chart

'Chart' is dynamic. I want to see if a dynamic property exists on Chart named LeftYAxis. What is the best way to do this on dynamic objects?

I don't think this is a duplicate of How to detect if a property exists on an ExpandoObject? because it doesn't discuss the best method to do this for dynamic objects.

like image 544
Randy Minder Avatar asked Jun 05 '12 14:06

Randy Minder


2 Answers

For a variety of reasons it's best to avoid try/catch blocks for control flow. Therefore, while Christopher's method attains the desired result, I find this preferable:

this.ChartDetails.Chart.GetType().GetProperty("LeftYAxis") != null;
like image 153
joelmdev Avatar answered Sep 20 '22 12:09

joelmdev


bool isDefined = false;
object axis = null;
try
{
    axis = this.ChartDetails.Chart.LeftYAxis;
    isDefined = true;
}
catch(RuntimeBinderException)
{ }

This is what happens at runtime in the first place. (When you access a property the 'dynamic' piece of things only happens when a first-chance exception gets handled by the object's override of DynamicObject's TryGetMember and TrySetMember

Some objects (like ExpandoObject) are actually dictionaries under the hood and you can check them directly as follows:

bool isDefined = ((IDictionary<string, object>)this.ChartDetails.Chart)
    .ContainsKey("LeftYAxis");

Basically: without knowing what actual type ChartDetails.Chart is (if it's an ExpandoObject a plain ol' subclass of object or a subclass of DynamicObject) there's no way besides the try/catch above. If you wrote the code for ChartDetails and Chart or have access to the source code you can determine what methods exist for the object and use those to check.

like image 42
Chris Pfohl Avatar answered Sep 22 '22 12:09

Chris Pfohl