Check if property exists in C # Expando class

I would like to know if a property exists in a C # Expando class.

as a hasattr function in python. I would like C # to equal for hasattr.

something like that...

if (HasAttr(model, "Id")) { # Do something with model.Id } 
+8
c # dynamic expandoobject
source share
2 answers

Try:

 dynamic yourExpando = new ExpandoObject(); if (((IDictionary<string, Object>)yourExpando).ContainsKey("Id")) { //Has property... } 

ExpandoObject explicitly implements IDictionary<string, Object> , where the key is the name of the property. Then you can check if the dictionary contains a key. You can also write a small helper method if you need to perform this kind of check often:

 private static bool HasAttr(ExpandoObject expando, string key) { return ((IDictionary<string, Object>) expando).ContainsKey(key); } 

And use it like this:

 if (HasAttr(yourExpando, "Id")) { //Has property... } 
+21
source share

According to the answer, vcsjones will be even nicer:

 private static bool HasAttr(this ExpandoObject expando, string key) { return ((IDictionary<string, Object>) expando).ContainsKey(key); } 

and then:

 dynamic expando = new ExpandoObject(); expando.Name = "Test"; var result = expando.HasAttr("Name"); 
0
source share

All Articles