Invoke a member of a dynamic object with a name defined at runtime in a String

Viewed 2837

I want to access a property on an object while leveraging the DLR binding mechanism.

  • I cannot use the native binding mechanism (dynamic keyword in C#) because I do not know the property name at compile-time;
  • I cannot use reflection because it only retrieves static type information;
  • casting to an IDictionary<string, object>, to my knowledge, only solves the case of dynamic classes that choose to implement that interface (such as ExpandoObject).

Here is the demonstration code:

    static void Main(string[] args)
    {
        dynamic obj = new System.Dynamic.ExpandoObject();
        obj.Prop = "Value";
        // C# dynamic binding.
        Console.Out.WriteLine(obj.Prop);
        // IDictionary<string, object>
        Console.Out.WriteLine((obj as IDictionary<string, object>)["Prop"]);
        // Attempt to use reflection.
        PropertyInfo prop = obj.GetType().GetProperty("Prop");
        Console.Out.WriteLine(prop.GetValue(obj, new object[] { }));
        Console.In.ReadLine();
    }
5 Answers
Related