Creating empty objects - empty class with empty properties / subclasses C #

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 a new instance of Human, I need to do Human person = new Human(); But when I try to access, like person.properties.prop1=1; , then I have nullRefrence in the properties, beacuse, I must also create new properties. I have to do this:

 Human person = new Human(); person.properties = new HumanProperties(); 

and now I can access this person.properties.prop1=1;

This was a small example, but I have a huge class created from xsd, and I don’t have much time to manually generate this “person” class with all its subclasses. Is there a way to do this programmatically or is there some kind of generator for this?

Or can I skip the class and make a new typeof type of property for each property and attach it to the parent class?

Thanks!

+4
source share
4 answers

I don’t know if there is a usual way to do what you ask, since the default type for classes is null . However, you can use reflection for a recursive loop through properties, look for public properties with constructors without parameters and initialize them. Something like this should work (unverified):

 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 it like this:

 var human = new Human(); InitProperties(human); 
+7
source

I would suggest using a constructor:

 public class Human { public Human() { Properties = new HumanProperties(); } public int Age {get; set;} public HumanProperties Properties {get; set;} } 
+3
source

You can change the class declaration as follows:

 public class Human { int age; HumanProperties properties = new HumanProperties(); } 
+1
source

.NET uses properties.

You can use the Visual Studio keyboard shortcut: Ctrl + r, Ctrl + e to automatically create a property.

Try the following:

 public class HumanProperties { public int Prop1 { get { return _prop1; } set { _prop1 = value; } } private int _prop1 = 0; public int Prop2 { get { return _prop2; } set { _prop2 = value; } } private int _prop2; public string Name { get { return _name; } set { _name = value; } } private string _name = String.Empty; } public class Human { public int Age { get { return _age; } set { _age = value; } } private int _age = 0; public HumanProperties Properties { get { return _properties; } set { _properties = value; } } private HumanProperties _properties = new HumanProperties(); } 
0
source

All Articles