Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects containing list of same object type

Tags:

c#

oop

Is there anything wrong with defining something like this:

     class ObjectA
      {
         property a;
         property b;
         List <ObjectA> c;
         ...
      }
like image 399
zsharp Avatar asked Dec 04 '22 18:12

zsharp


2 Answers

No, and because the answer needs at least 30 characters, I'll add that this is a common pattern.

Since you included the oop tag, though, I'll add that this pattern gives a lot of control to the outside world. If c is a list of children, for example, you're giving everyone who has access to an instance of ObjectA the ability to add, delete, or replace its children.

A tighter approach would be to use some sort of read-only type (perhaps implementing IList<ObjectA>) to expose the children.

EDIT

Note that the following still allows others to modify your list:

 class ObjectA 
  { 
     property a; 
     property b; 
     List <ObjectA> c; 
     ... 
     public List<ObjectA> Children { get { return c; } }
  } 

The absence of a setter only prevents outsiders from replacing the list object.

like image 200
phoog Avatar answered Dec 24 '22 19:12

phoog


Nope. That's perfectly acceptable. Tree structures do this.

like image 34
Daniel A. White Avatar answered Dec 24 '22 19:12

Daniel A. White