Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

empty-class

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!

like image 805
Muno Avatar asked Feb 25 '13 06:02

Muno


Video Answer


3 Answers

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); 
like image 154
Eren Ersönmez Avatar answered Sep 22 '22 07:09

Eren Ersönmez


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;}
}
like image 33
Jens Kloster Avatar answered Sep 23 '22 07:09

Jens Kloster


You can change your class declaration to this:

public class Human
{
    int age;
    HumanProperties properties = new HumanProperties();
}
like image 31
MarcinJuraszek Avatar answered Sep 20 '22 07:09

MarcinJuraszek