0
votes

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.

2

2 Answers

1
votes

well you can always use Linq. programs.Cast<IDisposable>() gives you an IEnumerable<IDisposable>

EDIT: If you really need to return an IList but want to actually return some read only collection:

return new ReadOnlyCollection<IDisposable>( programs.Cast<IDisposable>().ToList() );

0
votes

No casting is needed if you use an interface List as below:

List<IDisposable> programs = new List<IDisposable>();
programs.Add(new Program());

Do this to return it as readonly:

public IEnumerable<IDisposable> GetReadOlnly() 
{
    return programs.Skip(0);
} 

To return a readonly IList:

public IList<IDisposable> GetReadOlnly() 
{
    return programs.AsReadOnly();
}