0

I went to an interview recently and there they asked me the following question:

Write a component to travel through an object hierarchy based on the data path passed in and return the value of the property implemeting the following method:

Public object getValueFromPath(object parentObj, string dataPath);

The object hierarchy will be some thing like this:

Object1
  objectRef2
    property1
    property2

parentObj will be Object1

dataPath will be objectRef2.property2

Can some one give me an idea how I can do that.

Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
PushCode
  • 1,419
  • 3
  • 15
  • 31
  • That doesn't seem like a very clear interview question. – scott.korin Mar 12 '13 at 01:47
  • 2
    @scott, seems clear enough to me. It's trying to guage the interviewee's familiarity with reflection. This is about as canonical and trivial a reflection question you could ask, so it seems fair to me. – Kirk Woll Mar 12 '13 at 01:48
  • @Kirk now that the question has been edited, I get it :) – scott.korin Mar 12 '13 at 01:49
  • Maybe it was a 'trick' question. And the correct answer is "the requirements are confusing, could you clarify then?" – Steve Wellens Mar 12 '13 at 01:50
  • Any ideas or short code snippet that I can use to implement this? – PushCode Mar 12 '13 at 01:52
  • [This](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp), along with Andrew's answer, might get you close to answering your question. – scott.korin Mar 12 '13 at 01:56

1 Answers1

5

You would need to use reflection.

First step would be to split the dataPath on ., and get a reference to the System.Type object representing the type of parentObj (parentObj.GetType()).

Then for each element in the path you would use something like .GetMember(...) on the Type object to find the member with that name, and update the current Type object accordingly.

Once you get to the property at the end, and you have the associated ProprtyInfo object, you then need to call .GetValue(...) to get the value of the property.

Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
  • Thanks @@Andrew. I am very new to reflection. Can you please give a short code snippet that I can work it on? – PushCode Mar 12 '13 at 01:58
  • 1
    @HRK, he could, but you would be far better served just reading up on the API docs ([System.Type](http://msdn.microsoft.com/en-us/library/system.type.aspx), [Type.GetProperty](http://msdn.microsoft.com/en-us/library/kz0a8sxy.aspx), etc.). It's not a very difficult API, and it's clear you haven't exercised it much, so it's time for you to play with the API and figure out how it works. – Kirk Woll Mar 12 '13 at 02:16
  • Sure then. I'll try to figure it out and will get back if I had any issues. – PushCode Mar 12 '13 at 02:19