Hi, I have Below code, which builds the object structure and populates it using some dummy data like so.
object[] dataMap = new object[]
{
(byte) 1,
new byte[] {1,0},
(int) 1,
new int[]{1,0},
(double) 1.111111,
new double[] {1.1111, 2.222222},
(float) 1.111,
new float[] {(float)1.111, (float)2.222},
(bool) false,
new bool[] {false, true},
(string) "ABCD",
new string[]{"ABCD", "WXYZ"},
(DateTime) DateTime.Now,
new DateTime[] {DateTime.Now, DateTime.Today}
};
Now I have to fill up the //TODO parts of this code, Where the 1st TODO is about, Filling in the data for item types, where the object can resemble any of the elements avaliable like string or a class.
and the 2nd TODO is about populating an array of a type of IWrapper.
Please help me out on this. I am new to C# and I have to submit this tomorrow. Below is the code snippet.
Thanks in advance.
private object[] BuildObjectStructure(object obj)
{
object[] retVal = new object[] { obj };
Type t = obj.GetType();
try
{
foreach (PropertyInfo pi in t.GetProperties())
{
if (pi.Name != "RawData")
{
bool assigned = false;
foreach(object data in dataMap)
{
if(data.GetType().Equals(pi.PropertyType))
{
pi.SetValue(obj, data, null);
assigned = true;
break;
}
}
if (!assigned)
{
if (pi.PropertyType.IsArray)
{
Type typ = pi.PropertyType.GetElementType();
if (typ.IsInterface)
{
object[] objI = new object[1];
objI[0] = Activator.CreateInstance(typ);
BuildObjectStructure((object)objI[0]);
}
else
{
object[] objI = new object[1];
objI[0] = Activator.CreateInstance(typ);
BuildObjectStructure((object)objI[0]);
}
}
else
{
object val = pi.GetValue(obj, null);
if (val != null)
{
BuildObjectStructure(val);
}
}
}
}
}
}
catch (Exception e)
{
}
return retVal;
}
Unnecessary code tags removed indentation and empty lines reduced