9

I'm looping through a property on a dynamic object looking for a field, except I can't figure out how to safely evaluate if it exists or not without throwing an exception.

        foreach (dynamic item in routes_list["mychoices"])
        {
            // these fields may or may not exist
           int strProductId = item["selectedProductId"];
           string strProductId = item["selectedProductCode"];
        }
Majid
  • 13,853
  • 15
  • 77
  • 113
MikeW
  • 4,749
  • 9
  • 42
  • 83
  • possible duplicate of [dynamic, How to test if a property is available](http://stackoverflow.com/questions/2998954/dynamic-how-to-test-if-a-property-is-available) – Kevin Nacios Jul 03 '13 at 03:40
  • why are you trying to use foreach (dynamic item ant to just var – COLD TOLD Jul 03 '13 at 03:40
  • This is the best answer http://stackoverflow.com/questions/2839598/how-to-detect-if-a-property-exists-on-a-dynamic-object-in-c – Ehsan Jul 03 '13 at 04:37
  • possible duplicate of [How to check whether an object has certain method/property?](http://stackoverflow.com/questions/5114469/how-to-check-whether-an-object-has-certain-method-property) – hazzik May 24 '15 at 22:56

3 Answers3

5

using reflection is better than try-catch, so this is the function i use :

public static bool doesPropertyExist(dynamic obj, string property)
{
    return ((Type)obj.GetType()).GetProperties().Where(p => p.Name.Equals(property)).Any();
}

then..

if (doesPropertyExist(myDynamicObject, "myProperty")){
    // ...
}
Chtioui Malek
  • 11,197
  • 1
  • 72
  • 69
2

This is gonna be simple. Set a condition which checks the value is null or empty. If the value is present, then assign the value to the respective datatype.

foreach (dynamic item in routes_list["mychoices"])
        {
            // these fields may or may not exist

            if (item["selectedProductId"] != "")
            {
                int strProductId = item["selectedProductId"];
            }

            if (item["selectedProductCode"] != null && item["selectedProductCode"] != "")
            {
                string strProductId = item["selectedProductCode"];
            }
        }
Shafiq Abbas
  • 484
  • 1
  • 5
  • 18
  • You check `selectedProductId` in both `if` statements. – Saber Amani Jul 03 '13 at 04:14
  • 1
    the property itself is possibly missing from the dynamic object , not the value - so standard null check throws invocation exception - try{}catch{} seems to do the job though – MikeW Jul 05 '13 at 09:45
-1

You need to surround your dynamic variable with a try catch, nothing else is the better way in makking it safe.

try
{
    dynamic testData = ReturnDynamic();
    var name = testData.Name;
    // do more stuff
}
catch (RuntimeBinderException)
{
    //  MyProperty doesn't exist
} 
123 456 789 0
  • 10,565
  • 4
  • 43
  • 72
  • Oh no! You try to use Exceptions in logic, while just need to check your property in a list (casting to ExpandoObject or using reflection). Instead of that you call a nuclear bomb - causes and the handle exception. – Artem A Mar 19 '21 at 14:38