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?
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.
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>(),
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With