0

I'm working on the expando object in C#, however, I would like to know whether we have a way to assign a predefined value like 'Prop not found' when we access to a non-existing property ? My code is as follow, if we access to an unknown property in the Dictionary (cast as expandoObject) I have the Runtimebinderexception.

var dict = new ExpandoObject() as IDictionary<string, object>;

     foreach (var item in xmldoc.Root.Elements("test"))
     {
          dict .Add(item.Attribute("key").Value, item.Element("value").Value);
     }

/*Existing key, it works fine*/ var testKey = dict.TestData

/*For non existing key in the dictionary*/ var testKey = dict.NewKey; /*I have an exception here*/

So is there any way to avoid an exception and display a value like above (Prop not found) ? Thanks

  • Why not catch the exception and then return "Prop not found"? – Domysee Apr 01 '16 at 06:13
  • @Domysee the problem is this dictionary will later be passed to the View, and cast to dynamic type variable where we access to dict.NewKey, and as the convention of our team, I unfortunately cannot put any catch exception. – Blue Cross Apr 01 '16 at 06:16

0 Answers0