How are properties for a Collection set?
I\'ve created a class with a Collection properties. I want to add to the List anytime I set a new value. Using _name.Add(val
It would be inappropriate for it to be part of the setter - it's not like you're really setting the whole list of strings - you're just trying to add one.
There are a few options:
AddSubheading
and AddContent
methods in your class, and only expose read-only versions of the listsIn the second case, your code can be just:
public class Section
{
public String Head { get; set; }
private readonly List _subHead = new List();
private readonly List _content = new List();
// Note: fix to case to conform with .NET naming conventions
public IList SubHead { get { return _subHead; } }
public IList Content { get { return _content; } }
}
This is reasonably pragmatic code, although it does mean that callers can mutate your collections any way they want, which might not be ideal. The first approach keeps the most control (only your code ever sees the mutable list) but may not be as convenient for callers.
Making the setter of a collection type actually just add a single element to an existing collection is neither feasible nor would it be pleasant, so I'd advise you to just give up on that idea.