I have a class that contains a private List. I have created a getter and a method to add elements to the list:
public class Test{
private List<T> myList;
public List<T> MyList
{
get { return myList; }
}
public Test()
{
myList = new List<T>();
}
public void AddElements(T element)
{
// Do dome stuff, subscribe to an event of T
myList.Add(element);
}
}
Since everytime an element is added to my list I want to do more things, I do not want that in some part of the code someone add an element directly:
Test test = new Test();
// Wrong
test.MyList.Add(element);
// Right
test.AddElements(element);
I have thought on creating a new class that implements the IList interface and overrides the Add() method, but I was wondering if there is a more simple/elegant way on "block" this Add() method.