Is it possible to create a ReadOnlyCollection without creating a copy of the list? Since the elements can be casted to its base class it should be safe for ReadOnlyCollection to return not the concrete type but the implemented interface.
Edit1 Adapted Code to show that I need to return IList to keep API compatibility.
public class Program : IDisposable
{
List<Program> Programs = new List<Program>();
public IList<IDisposable> Getter
{
get
{
var readOnly = new ReadOnlyCollection<IDisposable>(Programs);
return readOnly;
}
}
static void Main(string[] args)
{
}
public void Dispose()
{
}
}
This will not compile for obvious reasons but is there no e.g.
ReadOnlyCollectionCast<Program,IDisposable>
which will cast to IDisposable in the getter?
A bit more history how I got there. I did refactor a class did have List<IDisposable>
as class member. I needed for better serialization perf the concrete type in the data container. Changing the private field from List<IDisposable>
to List<Program>
is no problem but the public property should stay unchanged and still return an IList<IDisposable>
as a read only list.