Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read only observable collection

I have my class that has an internal observable collection. I want to pass the data in this to a user of the class via a function.

I don't want them to be able to change the objects inside of the observable collection or the collection itself.

What is the best way to do this performance and ease of use wise?

like image 608
zachary Avatar asked May 19 '10 18:05

zachary


2 Answers

Probably using this: ReadOnlyObservableCollection<T>. Note that you will have to write your own read-only wrappers for your objects, since the ReadOnlyObservableCollection<T> only prevents updates to the collection itself.

like image 111
Stephen Cleary Avatar answered Nov 20 '22 17:11

Stephen Cleary


I don't like using ReadOnlyObservableCollection<T> as it seems like a mistake / broken class; I prefer a contract based approach instead.

Here is what I use that allows for covarience:

public interface INotifyCollection<T> : ICollection<T>, INotifyCollectionChanged
{
}

public interface IReadOnlyNotifyCollection<out T> : IReadOnlyCollection<T>, INotifyCollectionChanged
{
}

public class NotifyCollection<T> : ObservableCollection<T>, INotifyCollection<T>, IReadOnlyNotifyCollection<T>
{
}

public class Program
{
    private static void Main(string[] args)
    {
        var full = new NotifyCollection<string>();
        var readOnlyAccess = (IReadOnlyCollection<string>) full;
        var readOnlyNotifyOfChange1 = (IReadOnlyNotifyCollection<string>) full;

        //Covarience
        var readOnlyListWithChanges = new List<IReadOnlyNotifyCollection<object>>()
            {
                new NotifyCollection<object>(),
                new NotifyCollection<string>(),
            };
    }
}
like image 20
Meirion Hughes Avatar answered Nov 20 '22 15:11

Meirion Hughes