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

I iterate over the property of a dynamic object looking for a field, but I cannot figure out how to safely evaluate whether 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"]; } 

thanks for the help

Hooray!

+7
c #
source share
3 answers

You need to surround the dynamic variable with try catch, nothing else will help in safe handling.

 try { dynamic testData = ReturnDynamic(); var name = testData.Name; // do more stuff } catch (RuntimeBinderException) { // MyProperty doesn't exist } 
+1
source share

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")){ // ... } 
+1
source share

It will be easy. Define a condition that checks for null or null. If a value is present, assign the value to the appropriate data type.

 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"]; } } 
0
source share

All Articles