1

let's say I have these classes :

internal class A
{
    public B Field { get; set; }
}

internal class B
{
    public int SubField { get; set; }
}

Is it possible to do something like this :

    var a = new A();
    a.Field = new B();
    a.Field.SubField = 10;

    dynamic d = a;
    var path = "Field.SubField";

    var i = d.path; // How to look for field <Field.SubField> instead of field <path>?
illegal-immigrant
  • 8,089
  • 9
  • 51
  • 84

2 Answers2

9

You can do this with reflection.

static object ReflectOnPath(object o, string path) {
    object value = o;
    string[] pathComponents = path.Split('.');
    foreach (var component in pathComponents) {
        value = value.GetType().GetProperty(component).GetValue(value, null);
    }
    return value;
}

There is absolutely no error checking in the above; you'll have to decide how you want to do that.

Usage:

var a = new A();
a.Field = new B();
a.Field.SubField = 10;

string path = "Field.SubField";
Console.WriteLine(ReflectOnPath(a, path));

You could even make this an extension method so that you can say

Console.WriteLine(a.ReflectOnPath("Field.SubField"));
jason
  • 236,483
  • 35
  • 423
  • 525
  • This is what I was going for. For error checking, there's the possibility that `GetProperty` could return null, and then there is the possibility that `GetValue` could return null. In either case, you could get a NRE if you evaluate further. – Anthony Pegram Dec 17 '10 at 19:25
  • 1
    Yes, right, reflection is pretty good solution in this case.I just wanted to know if it is possible using dynamic. – illegal-immigrant Dec 17 '10 at 19:27
1

It is not possible to do what you want using dynamic. dynamic just isn't intended for that.

First, think what the behaviour should be if you do:

dynamic d = a;
var path = "Field.SubField";

var i = d.path

and class A has for its own a field "path".

Trying to access a.Field.Subfield by means of a.path (which means a."FieldSubfield") it's just syntactically incorrect. If you want to achieve this, Jason wrote a very nice example of how you can do it (through reflection).

Andrei Pana
  • 4,484
  • 1
  • 26
  • 27