I have this string
Member.User.Name
and this instance:
Root root = new Root();
root.Member.User.Name = "user name";
How do I extract the value from root of the member Member.User.Name
for example:
string res = GetDeepPropertyValue(root, "Member.User.Name");
res will be "user name"
Thanks
Try this:
public object GetDeepPropertyValue(object instance, string path){
var pp = path.Split('.');
Type t = instance.GetType();
foreach(var prop in pp){
PropertyInfo propInfo = t.GetProperty(prop);
if(propInfo != null){
instance = propInfo.GetValue(instance, null);
t = propInfo.PropertyType;
}else throw new ArgumentException("Properties path is not correct");
}
return instance;
}
string res = GetDeepPropertyValue(root, "Member.User.Name").ToString();
NOTE: We don't need recursive solution for this because the number of loops is known beforehand. Using foreach would be more efficient if possible. We use recursion only when the implementation becomes complicated with for - foreach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With