I must preface that this is not an answer to the question, but an educational exterior.
As others have explained, you misunderstand the use of the PropertyInfo class. This class is used to describe a property and does not contain instance-related data. Therefore, what you are trying to do is impossible without additional information.
The PropertyInfo class can now retrieve instance-related data from an object, but you must have an object instance to read the data.
For example, take the following class structure.
public class Child { public string name = "S"; public string age = "44"; } public class Parent { public Parent() { Child = new Child(); } public Child Child { get; set; } }
The Child property is a property of the Parent class. When the parent class is built, an instance of Child is created as part of the Parent instance.
Then we can use Reflection to get the value of the Child property by a simple call.
var parent = new Parent(); var childProp = typeof(Parent).GetProperty("Child"); var childValue = (Child)childProp.GetValue(parent);
This works great. The important part is (Child)childProp.GetValue(parent) . Note that we are invoking the GetValue(object) method of the PropertyInfo class to get the value of the Child property from an instance of the Parent class.
This is fundamental, as you will need to develop a method for accessing property data. However, since we have listed several times, you must have an instance of the property. Now we can write an extension method that will facilitate this call. As I can see, there is no advantage to using the extension method, since the existing PropertyInfo.GetValue(object) method is quite easy to use. However, if you want to create a new instance of the parent object, then get the value, then you can write a very simple extension method.
public static TPropertyType ConvertToChildObject<TInstanceType, TPropertyType>(this PropertyInfo propertyInfo, TInstanceType instance) where TInstanceType : class, new() { if (instance == null) instance = Activator.CreateInstance<TInstanceType>();
Now this extension method simply accepts the instance as the second parameter (or the first in the extension call).
var parent = new Parent(); parent.Child.age = "100"; var childValue = childProp.ConvertToChildObject<Parent, Child>(parent); var childValueNull = childProp.ConvertToChildObject<Parent, Child>(null);
results
childValue = name: S, age: 44 childValueNull = name: S, age: 100
Note the importance of having an instance.
One Caveat: The extension method will create a new instance of the object if the object is null, calling:
if (instance == null) instance = Activator.CreateInstance<TInstanceType>();
You will also notice that typeparam TInstanceType must be a class and must confirm the new() constraint. This means that it must be a class and must have a constructor without parameters.
I understand that this is not a solution to the issue, but I hope this helps.