Check If A Property Exists On a Dynamic Anonymous Type In C#


In this post, we will present possible solutions for checking if a property exists on a dynamic anonymous type in C#. My situation is straightforward my question is how to check, without throwing an exception, whether a certain property is available on my dynamic variable without needing to know the type of the object so basicaly we cab to check if a property is available on a dynamic variable.

Considering an object type as Pets information with fields like Id, PetName, PetCategory, and Breed, we can handle it dynamically in C# using the ExpandoObject class.

Here we have a dynamic object to represent Pets information:

        dynamic pet = new ExpandoObject();
        pet.Id = 1;
        pet.PetName = "Buddy";
        pet.PetCategory = "Dog";
        pet.Breed = "Golden Retriever";
        
Check if Property Exists: We can then check if properties like Id, PetName, PetCategory, and Breed exist on the dynamic object:
        var petInfo = pet as IDictionary<string, object>;
        if (petInfo.ContainsKey("PetName"))
        {
            // PetName property exists
            Console.WriteLine("PetName property exists: " + pet.PetName);
        }
        else
        {
            // PetName property does not exist
            Console.WriteLine("PetName property does not exist.");
        }
        

Here's a function in C# named IsPropertyKeyExistInObject that checks if a property key exists in a dynamic object representing pets information:

    public static bool IsPropertyKeyExistInObject(dynamic pets, string PetName)
    {
        if (pets is ExpandoObject)
            return ((IDictionary<string, object>)pets).ContainsKey(PetName);

        return pets.GetType().GetProperty(PetName) != null;
    }
  

This function first checks if the pets object is of type ExpandoObject. If it is, it casts the object to IDictionary<string, object> and uses the ContainsKey method to check if the property key exists.

If the pets object is not of type ExpandoObject, it assumes it's a regular object and uses reflection to check if the property exists using GetType().GetProperty(PetName).

This function provides a flexible way to determine the existence of properties in dynamic objects, allowing for dynamic handling of property checks.

Using this approach we can handle Pets information dynamically, making it convenient to work with objects of varying structures at runtime.

Here we are creating an extension method in C# for checking if a property key exists in a dynamic object representing pets information:

    public static class DynamicExtensions
    {
        public static bool IsPropertyKeyExist(this dynamic pets, string propertyName)
        {
            if (pets is ExpandoObject)
                return ((IDictionary<string, object>)pets).ContainsKey(propertyName);

            return pets.GetType().GetProperty(propertyName) != null;
        }
    }
  

Advantange of that extension method is that it can be used on any dynamic object to check for the existence of a property key. 

Simply call the function on the dynamic object and pass the property name as an argument.

example:

    dynamic pet = new ExpandoObject();
    pet.PetName = "Buddy";

    bool isPropertyExists = pet.IsPropertyKeyExist("PetName");
    Console.WriteLine("Does PetName property exist? " + isPropertyExists);
  
2

 Checks if a property exists on a dynamic object. It first determines the type of the object and then performs the property check accordingly.

    public static bool HasProperty(dynamic targetObject, string propertyName)
    {
        Type targetType = targetObject.GetType();

        if (targetType == typeof(ExpandoObject))
        {
            return ((IDictionary<string, object>)targetObject).ContainsKey(propertyName);
        }

        return targetType.GetProperty(propertyName) != null;
    }
  


3

This CheckPropertyExistenceAndNotNull, checks if a property exists on a dynamic object and ensures that it is not null. It handles various types of dynamic objects, including ExpandoObject, IDictionary<string, object>, IDictionary<string, JToken>, and DynamicJsonObject.

    public static bool CheckPropertyExistenceAndNotNull(dynamic targetObject, string propertyName)
    {
        if (targetObject == null) return false;
        
        if (targetObject is ExpandoObject)
        {
            var dictionary = (IDictionary<string, object>)targetObject;
            if (dictionary.ContainsKey(propertyName))
                return dictionary[propertyName] != null;
            return false;
        }

        if (targetObject is IDictionary<string, object> dictionary1)
        {
            if (dictionary1.ContainsKey(propertyName))
                return dictionary1[propertyName] != null;
            return false;
        }

        if (targetObject is IDictionary<string, JToken> dictionary2)
        {
            if (dictionary2.ContainsKey(propertyName))
                return (dictionary2[propertyName].Type != JTokenType.Null && dictionary2[propertyName].Type != JTokenType.Undefined);
            return false;
        }

        if (targetObject is DynamicJsonObject dynamicJsonObject)
        {
            return dynamicJsonObject.ContainsKey(propertyName) && dynamicJsonObject[propertyName] != null;
        }

        var propertyInfo = targetObject.GetType().GetProperty(propertyName);
        if (propertyInfo != null)
            return propertyInfo.GetValue(targetObject) != null;
        
        return false;
    }
  


4

We encountered a scenario where the existing solutions for checking property existence on dynamic objects from JSON data weren't effective. we found a solution provided to handle property access on dynamic objects.

    public static bool CheckPropertyExistence(dynamic targetObject, string propertyName)
    {
        try
        {
            var value = targetObject[propertyName];
            return true;
        }
        catch (KeyNotFoundException)
        {
            return false;
        }
    }
  


5 My code is compatible with various types such as anonymous types, ExpandoObject, Nancy.DynamicDictionary, or any other object that can be cast to IDictionary.


    public static bool CheckPropertyExistence(dynamic targetObject, string propertyName) {
        if (targetObject == null) return false;
        if (targetObject is IDictionary dictionary) {
            return dictionary.ContainsKey(propertyName);
        }
        return targetObject.GetType().GetProperty(propertyName) != null;
    }
  

It checks if a property exists on a dynamic object. It first checks if the object is null, then determines its type, and performs the property check accordingly.

6 This code,shows you simple approach for checking if a property exists on a dynamic object in C# using reflection and exception handling and it provides a flexible way to work with dynamic objects and handle property access dynamically.
 
using System;

class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        dynamic dynamicObject = new Customer { Name = "John", Age = 30 };

        if (HasProperty(dynamicObject, "Name"))
        {
            Console.WriteLine("Name property exists.");
        }
        else
        {
            Console.WriteLine("Name property does not exist.");
        }
    }

    static bool HasProperty(dynamic obj, string propertyName)
    {
        try
        {
            var value = obj.GetType().GetProperty(propertyName);
            return value != null;
        }
        catch
        {
            return false;
        }
    }
}
In above code we have a custom Customer class with properties Name and Age and then create an instance of this class and use it as a dynamic object. 
We create a new instance of the Customer and assign it to a dynamic variable dynamicObject and this dynamic variable allows us to access its properties dynamically.
We use the HasProperty method to check if the dynamicObject has a specific property, specified by the propertyName parameter and the HasProperty method takes two parameters: obj, which is the dynamic object we want to check, and propertyName, which is the name of the property we want to verify.

And inside the HasProperty method, we use a try-catch block to handle any exceptions that might occur when attempting to access the property. We use reflection (GetType().GetProperty(propertyName)) to retrieve the property by its name.

If the property exists (value != null), we return true. Otherwise, if an exception is caught, or if the property does not exist, we return false.