views:

51

answers:

2

.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?

+2  A: 
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.

Darin Dimitrov
SO users are so nice! :) +1 for not actually using the phrase "RTFM".
Stephen Cleary
The docs don't explain the OP's question.
Hans Passant
+3  A: 

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.

Femaref
Meh, doesn't explain the SROC(object) constructor.
Hans Passant
It does - even if you have an empty collection, you still should use the same locking objects as if you had elements in it. Of course, the possibility of errors is nonexistant (at least I can't think of an instance where it would be possible) but this way is more consistent.
Femaref
@Femaref: good comeback but then it doesn't explain the parameterless ctor.
Henk Holterman
If the only place a lock is needed is that Collection, there is no problem in using the internal one. Although there still is the point... why would you need a lock in an read-only collection anyway? If you compare it to the SynchronizedCollection, the ctors are exactly the same, so probably those exist to mirror that class. Accessing an element in a collection should be atomic anyway, so a locking object doesn't make sense in a read only collection. hm.
Femaref
I'm not completely convinced but I want to thank you for taking the question seriously.
TTT