2

My code below looks so complicated when making association between Parent and Child.

Question: What is the best way to associate Parent and Child data model object?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using ConsoleApplication1;

class Child
{
    public string Name { get; set; }
    public Parent Parent { get; set; }
}


class Parent
{
    public string Name { get; set; }
    public IEnumerable<Child> Children { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        Parent p1 = new Parent { Name = "P1" };

        Child c1 = new Child { Name = "C1" };
        c1.Parent = p1;

        Child c2 = new Child { Name = "C2" };
        c2.Parent = p1;


        List<Child> children = new List<Child>();
        children.Add(c1);
        children.Add(c2);

        p1.Children = children;
    }

}
Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165

3 Answers3

6

Maybe you should implement some helper methods into the class, which encapsulate some basic thinks:

public class Parent {

....
    public void AddChild(Child child) {
        child.Parent = this;
        this.Children.Add(child);
    }

    public void RemoveChild(Child child) {
        child.Parent = null;
        this.Children.Remove(child);
    }
}


public class Child {
    private Child() {}

    public static Child CreateChild(Parent parent) {
        var child = new Child();
        parent.AddChild(child);
        return child;
    }
}
MacX
  • 587
  • 5
  • 16
  • I would remove the chid.Parent = parent from the Child constructor, parent.AddChild does that already. u r just repeating yourself. Maybe make Child's constructor private, add a creater method, that takes parent as input and other properties, creates the child and uses parents' AddChild method (in short make it a singleton) – hazimdikenli Feb 07 '11 at 12:53
1

This question might help:

Tree data structure in C#

Community
  • 1
  • 1
bobwah
  • 2,454
  • 4
  • 33
  • 49
1
class Parent
{
  ...
  public Child AddChild(string name)
  {
    return this.AddChild(new Child(name));
  }

  public Child AddChild(Child c)
  {
    c.Parent = this;
    this.children.Add(c);

    return c;
  }
}
Jaroslav Jandek
  • 9,463
  • 1
  • 28
  • 30