In a C# class I have a list and two different getters for the list:
private List<A> a;
public List<A> EveryA
{
get
{
if (a == null) a = new List<A>();
return a;
}
}
public List<A> FilteredA
{
get
{
return EveryA.FindAll(a => a.IsInFilter);
}
}
Now my question is: how about the syntax FilteredA.Add(this);?
It compiles and runs but it cannot add any item to any list.
Should a better compiler have to notify the (small) problem?
They are not the same list. This is not something the compiler can check for you, since the compiler can’t really read your mind. Check the documentation for
List<T>.FindAllThe result is a list, but it isn’t the same list (how could it be? your original list isn’t filtered!).
You should be able to add items to the list returned by
FilteredA, except they won’t show up ina.I suggest you use LINQs
Whereinstead, returning anIEnumerable<T>. That way, it is obvious that the result ofFilteredAshouldn’t be changed, only iterated over: