I am using reflection to instantiate a class and insert values in its nested properties.
Here's an example of what im trying to do:
https://dotnetfiddle.net/pBgeeV
private static void ApplyValueToProperty(object entityInstance, Type instanceType, string propName, string propValue)
{
// Current only supports an object inside another object.
// Future TODO> GO RECURSIVE TO FIND AND INSTANTIATE ALL NESTED PROPERTIES OR CLASSES!
if (propName.Contains("."))
{
string[] splittedName = propName.Split('.');
// Get type of current property
PropertyInfo currentProp = instanceType.GetProperty(splittedName[0]);
Type nestedPropertyType = currentProp.PropertyType;
// Get current object applied to this current prop
var otherObject = currentProp.GetValue(entityInstance);
if (otherObject == null)
{
// Create instance of nested property class and set its value to a new instance
otherObject = Activator.CreateInstance(nestedPropertyType);
currentProp.SetValue(entityInstance, otherObject);
}
SetSafePropertyValue(otherObject, nestedPropertyType, splittedName[1], propValue);
}
else
{
SetSafePropertyValue(entityInstance, instanceType, propName, propValue);
}
}
- First I create the main class outside of this method scope. (Test class).
- Then all other propName will have the value of nested properties or classes, example:
I will have a name like "OtherTest.AnotherTest.Name",
- If 'Test' has another property of type 'OtherTest', it would create 'OtherTest' and then create 'AnotherTest' and then put value on correct 'Name'.
I would like to change the first if statement to be recursive and instantiate de correct class and insert values to the correct property. In the end I want to have a complete object created with my necessary properties instantiated and values applied.
Note: I want to avoid using GetProperties() because my class has lots of properties from base members, and it consumes a lot of memory.