Suppose I have this:
public class MyClass
{
private readonly List<string> _strings = new List<string>();
public IEnumerable<string> MyStrings
{
get
{
return _strings;
}
}
}
How can I prevent the following from actually adding to the member variable list of string?
var theClass = new MyClass();
((List<string>)theClass.MyStrings).Add("I do not want to be able to add this!");
Create a new type that "wraps" the sequence. While there are many ways of doing this, one fairly simple "hack" is to just use Select
on it with the identity transformation:
return _strings.Select(x=>x);
This will create a new object with it's own iterator that, internally, has a reference to the _strings
list. Due to that extra layer of indirection (and with the extra bonus of the type being a type internal to the language that is not valid to use outside of the language definition), the caller can no longer cast their way to the list.
If you want something that's a bit clearer to read that makes the intentions a bit more known, you can just make a new method for it:
public static IEnumerable<T> AsSequence<T>(this IEnumerable<T> sequence)
{
return sequence.Select(x => x);
}
(Feel free to name it whatever is clearest to you.)