Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely check if a dynamic object has a field or not

Tags:

c#

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"];
        }
like image 536
MikeW Avatar asked Jul 03 '13 03:07

MikeW


2 Answers

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")){
    // ...
}
like image 77
Chtiwi Malek Avatar answered Oct 26 '22 23:10

Chtiwi Malek


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"];
            }
        }
like image 27
Shafiq Abbas Avatar answered Oct 26 '22 23:10

Shafiq Abbas