here a solution is given to get value of a property of a class by supplying its name . now I wonder how I can do the same in this condition :
I have a class MyClass . this class ha a property of type Foo named foo . the Foo has a property of type Bar named bar . and bar has a string property named value .
properties are not static .
I want to be able to get value of foo.bar.value by passing the string "foo.bar.value" as propertyName . in other word I want to pass the property path to get its value .
is it possible ?
As You pointing to answer of the question here , You need to make use of Reglection to achieve same thing.
With help of reflection you can read value of property.
something like this,
you need a put the code in one function and than split string as per you requirement
Read for detail : http://www.csharp-examples.net/reflection-examples/
You can do this with a recursive method. Each call takes the value with the first word in path and call the method again with the rest of the part.
Assuming FOO is static, you can get the class from a string like this:
C# Reflection: How to get class reference from string?
...and then use the rest of the post you've linked to to get the property and value from there:
Get property Value by its stringy name
If FOO isn't static, you'll need to use reflection on the instance (which would negate the requirement to pass in the name of the class as a string, since you can get the class from the instance with GetType()) - remembering that Bar won't have a value in the class unless it is static.
This assumes that the properties are named like the classes. i.e. that the property of Type
Foo
is also namedFoo
. Without this assumption, the question is lacking some crucial information.You can use the
string.Split
method to separate the stringfoo.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 toGetValue
in the following iteration.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 originalMyClass
instance.