0

I'm looking for ideas on better/safe way to access variables when using dynamic keyword. Most of the time

 myDto.ipaddress = item["ipaddr"];

is perfectly fine, except sometimes these values aren't defined in the json and need to accessed without throwing a Null exception.

dynamic routes_list = json_serializer.DeserializeObject(System.Web.HttpUtility.UrlDecode(data));

  for (int i = 0; i < routes_list["routes"].Length; i++)
  {
       var item = routes_list["routes"][i]


       System.Collections.Generic.Dictionary<string, object> itemDict = item;              

       // having to repeat this too often
       object snmask= string.Empty;
       itemDict.TryGetValue("snmask", out snmask);
  }

Thanks

MikeW
  • 4,749
  • 9
  • 42
  • 83
  • http://stackoverflow.com/questions/2839598/how-to-detect-if-a-property-exists-on-a-dynamic-object-in-c – DeveloperGuo Mar 14 '14 at 01:10
  • 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) – nawfal Jul 19 '14 at 21:28

1 Answers1

-1

It is perfectly acceptable to explicitly check for the presence of the value, and only proceed if it meets your requirements.

I find it good practice to verify everything when reading data you cannot fully trust (which means most data from disk, external service, local API or user input).

Brendan Grant
  • 937
  • 7
  • 16