My CTO (Chief Technical Officer) asked me to come up with a way where he could write one single function in the base class, and have access to the all the properties of the child class. Here is what I came up with -
Base Class
class Assets
{
public Assets getPropertyVal(Assets asObj)
{
PropertyInfo[] propInfos = asObj.GetType().GetProperties();
string strAttributeValue = "10";
foreach (PropertyInfo propInfo in propInfos)
{
// Getting the value
var propValue = propInfo.GetValue(asObj, null);
// Setting the value
propInfo.SetValue(asObj, Convert.ChangeType(strAttributeValue, propInfo.PropertyType), null);
}
return asObj;
}
}
Child Class
class House : Assets
{
public int rooms{get; set;}
}
Program.cs file
class Program
{
static void Main(string[] args)
{
House hsObj = new House();
hsObj.rooms = 5;
Assets asObj = hsObj.getPropertyVal(hsObj);
// Returns asObj as JSON
}
}
Now this works fine, but I was just wondering if there was a better way to do this in C#.
Note that we do not know what properties will be present in the child class, so this will have to be determined at run-time.
UPDATE : Making it clear, I was just wondering if there is a better way to access the child class properties, one without using reflection. The important point to note is that we have no idea what properties a child class may have.
UPDATE #2 : I am working with a product that has many entities. These entities have different properties. I want to be able to access and work with all these properties in one single place. This function is exactly that. It's that one single place from where I can access all the data.
var propValue = asObj.rooms; asObj.rooms = (int) propValue;
. What exactly do you want? Do you want to copy of all properties from a child class to a base class? – GiselleConsole.WriteLine(hsObj.rooms);
. You may as well just get rid of thehsObj = (House)hsObj.getPropertyVal(hsObj);
line altogether. The reflection is completely wasted. Can you come up with a better example of what you're trying to accomplish? – Marchand