I'm struggling with the ExpandoObject.
I created the extension method for ExpandoObject as shown in the first class however, obj.HasProperty
throws an error ''System.Dynamic.ExpandoObject' does not contain a definition for 'HasProperty''
For a test, I created an extension method for the string with the second class. In this case, name.HasB()
works as expected however, obj.Name.HasB()
throws the same error as above.
Why is this happening and how do I fix it?
public static class ExpandoExtentions {
public static bool HasProperty(this ExpandoObject obj, string property) =>
(obj as IDictionary<string, object>).ContainsKey(property);
}
public static class StringExtensions {
public static bool HasB(this string s) => s.ToLower().Contains("b");
}
public class ExpandoTest {
public static void Main() {
string name = "Bob";
dynamic obj = new ExpandoObject();
obj.Name = name;
// Both objects return "... String"
Console.WriteLine($"name is a {name.GetType().Name}");
Console.WriteLine($"obj.Name is a {obj.Name.GetType().Name}");
// Works as expected
Console.WriteLine($"name has a b: {name.HasB()}");
// Throws Error
Console.WriteLine($"obj.Name has a b: {obj.Name.HasB()}");
// Throws Error
Console.WriteLine($"obj has a Name: {obj.HasProperty("Name")}");
}
}