I have two classes:
public class HumanProperties { int prop1; int prop2; string name;}
public class Human{int age; HumanProperties properties;}
Now if i want to create new instance of Human, i have to do Human person = new Human();
But when i try to access like person.properties.prop1=1;
then i have nullRefrence at properties, beacuse i have to make new properties too.
I have to make like that:
Human person = new Human();
person.properties = new HumanProperties();
and now i can access this person.properties.prop1=1;
This was small example, but i have huge class generated from xsd and i dont have so much time for generating manually this "person" class with all its subclasses. Is there some way how to do it programmatically or is there some generator for that?
Or can i loop through class and make for every property new class typeof property and join it to parent class?
Thanks!
I don't thing there is a conventional way to do what you're asking for as the default type for classes is null
. However, you can use reflection to recursively loop through the properties, looking for public properties with parameter-less constructors and initialize them. Something like this should work (untested):
void InitProperties(object obj)
{
foreach (var prop in obj.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanWrite))
{
var type = prop.PropertyType;
var constr = type.GetConstructor(Type.EmptyTypes); //find paramless const
if (type.IsClass && constr != null)
{
var propInst = Activator.CreateInstance(type);
prop.SetValue(obj, propInst, null);
InitProperties(propInst);
}
}
}
Then you can use this like so:
var human = new Human();
InitProperties(human);
I would suggest you use the constructor:
public class Human
{
public Human()
{
Properties = new HumanProperties();
}
public int Age {get; set;}
public HumanProperties Properties {get; set;}
}
You can change your class declaration to this:
public class Human
{
int age;
HumanProperties properties = new HumanProperties();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With