check to see if a property exists within a C# Expando class
Asked Answered
F

2

11

I would like to see if a property exist in a C# Expando Class.

much like the hasattr function in python. I would like the c# equalant for hasattr.

something like this...

if (HasAttr(model, "Id"))
{
  # Do something with model.Id
}
Fortunia answered 20/8, 2012 at 20:14 Comment(1)
possible duplicate of How to detect if a property exists on an ExpandoObject?Timmy
S
25

Try:

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

An ExpandoObject explicitly implements IDictionary<string, Object>, where the Key is a property name. You can then check to see if the dictionary contains the key. You can also write a little helper method if you need to do this kind of check often:

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

And use it like so:

if (HasAttr(yourExpando, "Id"))
{
    //Has property...
}
Seventeenth answered 20/8, 2012 at 20:16 Comment(0)
T
0

According to vcsjones answer it will be even nicer to:

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");
Topsail answered 13/4, 2013 at 10:30 Comment(2)
It would perhaps be nice, but C# won't allow an extension method on a dynamic object. See [#12502273.Downtown
What about adding a dynamic method named HasAttr to the expando object? Something like this: expando.HasAttr = new Func<bool>((string key) => ((IDictionary<string, Object>) expando).ContainsKey(key));Karelia

© 2022 - 2024 — McMap. All rights reserved.