Leroy Jenkins
Leroy Jenkins

Reputation: 2770

What access modifier to set for my Generic List?

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.

Upvotes: 0

Views: 175

Answers (1)

dcastro
dcastro

Reputation: 68710

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?

Upvotes: 2

Related Questions