2

I have an object:

MyObject obj = new MyObject();
obj.X = "Hello";
obj.Y = "World";

Someone passes me a string:

string myString = "obj.X";

I want to get the value referenced to myString, like this:

var result = <Some Magic Expression>(myString); // "Hello"    

Is it possible through reflection?

IS4
  • 11,945
  • 2
  • 47
  • 86
Max Bertoli
  • 614
  • 5
  • 25
  • 4
    I assumed this is C# (by the code) although I can also think of another language that'd compile in. Please verify this and elaborate a bit. – Benjamin Gruenbaum Jul 22 '15 at 11:36
  • 2
    Do you really want "obj.X" to be parsed or do you want to retrieve the value of the property "X" on the "obj" instance? – vc 74 Jul 22 '15 at 11:38
  • Language is C#. Well, the final result is to be able to associate a string variable "obj" to a real object so i can GetProperty of that object. Parsing "obj.X" would be the best... I see it hard... – Max Bertoli Jul 22 '15 at 11:44
  • Jon Skeet already answered this here: http://stackoverflow.com/questions/11107536/convert-string-to-type-c-sharp – Stephen Brickner Jul 22 '15 at 11:49
  • possible duplicate of [Get property value from string using reflection in C#](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – farid bekran Jul 22 '15 at 11:50
  • 1
    I would check out Roslyn. Here might be similar problem http://stackoverflow.com/questions/24733556/pass-object-instance-to-roslyn-scriptengine – Alex K. Jul 22 '15 at 12:03
  • The problem i can't find a solution is to get an object from a string name. – Max Bertoli Jul 22 '15 at 13:21
  • I don't think this is a duplicate, I haven't seen anyone else ask this. But I am curious - why do you want this behaviour? – TarkaDaal Jul 22 '15 at 13:45
  • The object doesn't have a "name", only the variable that you store it in. You can't access a variable by a string that contains its name. – IS4 Jul 22 '15 at 18:26

1 Answers1

0

You can't exactly replicate this behaviour, because names of local variables aren't saved in the method's metadata. However, if you keep a dictionary of objects, you can address the object by its key:

public static object GetProperty(IDictionary<string, object> dict, string path)
{
    string[] split = path.Split('.');
    object obj = dict[split[0]];
    var type = obj.GetType();
    return type.InvokeMember(split[1], BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty, null, obj, null);
}

 

var dict = new Dictionary<string, object>();
var cl = new MyClass();
dict["obj"] = cl;
cl.X = "1";
cl.Y = "2";
Console.WriteLine(GetProperty(dict, "obj.X"));
Console.WriteLine(GetProperty(dict, "obj.Y"));

This can handle accessing fields and properties in the format "name.property". Doesn't work for dynamic objects.

IS4
  • 11,945
  • 2
  • 47
  • 86