How to safely check if a dynamic object has a field or not
c#
Solution
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
}
Problem
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"]; } ```