• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 270
  • Last Modified:

C# - Delete ChildObject from ParentObject

Hi Experts,

I have a class as below

Class person
{
   public string Name{get;set;}
   public  person child{get;set;}
}
i need to delete child  from person.
i have used syntax as below
person p  = new person();

// based on certain condition  i am deleting as below
p.child = null;

Is this the right Approach or do we have an other Options to delete child object. Please advice.
0
B_Pati
Asked:
B_Pati
1 Solution
 
databoksCommented:
I believe your code is fine. Setting the value to NULL instead of string.Empty is better because then the variable does not have any value in the memory. In other words it doesn't exist.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
That looks fine to me as well.

If you need something else to occur when the child gets deleted, though, then you can add code in the "set" portion of the property:
    public class person
    {

        public string Name{get;set;}

        private person _child;
        public person child
        {
            get { return _child; }
            set 
            {
                if (value == null)
                {
                    if (_child != null)
                    {
                        // ... do something with existing child before deletion ...
                        Console.WriteLine("Before Child Deletion");
                    }
                }
                _child = value;
            }
        }

    }

Open in new window


What if a person has more than one child though?  You might want a List<person> to represent children instead...
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now