Question

.net class SynchronizedReadOnlyCollection has 4 constructors.

    public SynchronizedReadOnlyCollection();
    public SynchronizedReadOnlyCollection(object syncRoot);
    public SynchronizedReadOnlyCollection(object syncRoot, IEnumerable<T> list);
    public SynchronizedReadOnlyCollection(object syncRoot, params T[] list);

What is the use of the parameterless constructor and the constructor with only the lock object? The collection will always be empty if you don't fill the collection when you create the collection? Do I miss something?

Was it helpful?

Solution

At some point it is possible that you need an empty collection, e.g. if you are initializing a class and data isn't known when the constructor is called. If you don't assign an empty collection, other code might fail if it tries to access that field/property and throws a NullReferenceException. If data is supplied at a later stage, that code simply replaces the field with a new, filled instance of SynchronizedReaOnlyCollection.

OTHER TIPS

public SynchronizedReadOnlyCollection();

Initializes a new empty collection which will lock on an internal field.

public SynchronizedReadOnlyCollection(object syncRoot);

Initializes a new empty collection which will lock on an object you provide.

public SynchronizedReadOnlyCollection(object syncRoot, IEnumerable<T> list);

Initializes a new collection containing the elements in the list which will lock on an object you provide.

The documentation does a good job explaining this. It's worth reading.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top