This assumes that the properties are named like the classes. i.e. that the property of Type Foo
is also named Foo
. Without this assumption, the question is lacking some crucial information.
You can use the string.Split
method to separate the string foo.bar.value
at the dots. You will then have an array with one element per property name.
Iterate over that array and use PropertyInfo.GetValue
to retrieve the value of the properties. The value returned in one operation is the instance passed to GetValue
in the following iteration.
string props = "foo.bar.value";
object currentObject = // your MyClass instance
string[] propertyChain = props.Split('.');
foreach (string propertyName in propertyChain) {
if (propertyName == "") {
break;
}
PropertyInfo prop = currentObject.GetType().GetProperty(propertyName);
currentObject = prop.GetValue(currentObject);
if (currentObject == null) {
// somehow handle the situation that one of the properties is null
}
}
Update: I have added a safeguard to ensure this will work even if props
is empty. In that case, currentObject
will remain a reference to the original MyClass
instance.