Dynamic object. How to determine if a property is defined?

I have a dynamic object that looks like this:

this.ChartDetails.Chart

The "chart" is dynamic. I want to see if a dynamic property exists in the chart named LeftYAxis. What is the best way to do this on dynamic objects?

I do not think this is a duplicate. How to determine if a property exists in ExpandoObject? as it does not discuss the best way to do this for dynamic objects.

+5
source share
4 answers
bool isDefined = false;
object axis = null;
try
{
    axis = this.ChartDetails.Chart.LeftYAxis;
    isDefined = true;
}
catch(RuntimeBinderException)
{ }

, . ( , "" , DynamicObject TryGetMember TrySetMember

(, ExpandoObject) , :

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

: , ChartDetails.Chart ( ExpandoObject ol 'object DynamicObject), try/catch. ChartDetails Chart , , , , .

+6

try/catch . , , :

this.ChartDetails.Chart.GetType().GetProperty("LeftYAxis") != null;
+5

This works if the dynamic object is in json / open-standard format.

I made two different method assistants, one for the open standard format and one for the "standard object".

    // Checks if object typed json or xml has a specific property
    public static bool IsPropertyExistsOpenStandardFormat(dynamic dynamicObject, string propertyName)
    {
        try
        {
            var x = dynamicObject[propertyName];
            if (x != null)
                return true;
        }
        catch 
        {
            return false;
        }

    }

    // Checks if standard object has a specific property
    public static bool IsPropertyExistsStandard(dynamic dynamicObject, string propertyName)
    {
        return dynamicObject.GetType().GetProperty(propertyName) != null;
    }
+1
source

This one works -:

public static bool IsPropertyExists(dynamic dynamicObj, string property)
       {
           try
           {
               var value=dynamicObj[property].Value;
               return true;
           }
           catch (RuntimeBinderException)
           {

               return false;
           }

       }
-1
source

All Articles