0

Within my C# class is a Generic List. I would like to access the count of this list in my form.

Should I:
a) make the Generic List public
b) create a property to only access the Lists count method?
c) ??

b seems like the obvious choice but it adds a lot of extra code since it doesnt update dynamically. I have to manually update the variable (myCount = list.count) anytime the list is changed.

Just a novice just looking for some advice, Thanks.

rene
  • 41,474
  • 78
  • 114
  • 152
Leroy Jenkins
  • 2,680
  • 6
  • 25
  • 33

1 Answers1

2

According to the Law of Demeter, or principle of least knowledge, you should go with option B, and expose a get-only property that returns the list's Count property.

You don't need to manually update any variable, simply return the list's Count property.

public int ItemsCount
{
  get { return _innerList.Count; }
}

Of course, this isn't always a clear-cut case, it's a matter of semantics. It all depends on what the outer class and the list mean. The LoD is a general guideline, a principle, but not a rule. You've got to ask yourself: does it make sense to expose the list?

dcastro
  • 66,540
  • 21
  • 145
  • 155
  • I disagree in general. This boils down to the [inheritance vs composition discussion](http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance). The outer class should only expose the count if it is some logical property of that class, otherwise it should just expose the list. In this case it is hard to decide what way to choose because of the lack of context. – Vincent van der Weele Dec 14 '13 at 16:23