tags:

views:

37

answers:

2

Is there a efficient way to provide an Enumarable<SomeType> or a collection that implements INotifyCollectionChanged but that can only be changed from the inside of the providing class.

The following example shows what I mean, but has the disadvantage that the caller can cast the IEnumerable<SomeType> back and then manipulate my internal collection, what I really would dislike:

public class DemoClass{

    ObservableCollection<SomeType> m_collection=
                                   new ObservableCollection<SomeType>();

    public IEnumerable<SomeType> SomeTypeInstances{
         get{return m_collection;}
    }

    private void AMethod(){
        // Here I can work with m_collection            
    }

}

Is there an easy way, perhaps with the ObservableCollection, or is it necessary to write a wrapper that implements IEnumerable<SomeType> and INotifyCollectionChanged and then forwarding collectionchanged-evnets to the destination?

+1  A: 

Use ReadOnlyObservableCollection(T).

Franci Penov
Perfect! Excactly what I was looking for. Thanks
HCL
Glad to be of help. :-)
Franci Penov
+1  A: 

if you return the internal collection then they can always mess with your data. you could just give the user a ReadOnlyCollection<T> that is a clone of the internal data. That way, they can get to the data and your data isn't at risk of being corrupted.

Scott M.