buciz
buciz

Reputation: 73

Cannot add an item to the Collection property. Please hеlр me, please

I am trying to add an item to the SynchronizedCollection but it works only if I add it directly into the field.

        _s = new SynchronizedCollection<int>();
        _s.Add(01010);
        S.Add(123);

    private SynchronizedCollection<int>  _s;
    public SynchronizedCollection<int> S
    {
        get
        {

            lock (_s.SyncRoot)
            {
                return new SynchronizedCollection<int>(_s.SyncRoot, _s);
            }
        }

        private set
        {
            _s= value;
        }
    }

How to make it work?

Upvotes: 0

Views: 168

Answers (2)

Johnny
Johnny

Reputation: 9519

it works only if I add it directly into the field

Because you didn't assign newly created SynchronizedCollection to _s. Every time you call S getter the new collection is created, all elements are copied, and the element is added to it. _s actually stays untouched.

lock (_s.SyncRoot)
{
    _s = new SynchronizedCollection<int>(_s.SyncRoot, _s);
    return _s;
}

Although I don't think it is needed to create new collection each time, SynchronizedCollection itself is thread-safe so you could just return _s but don't know actual scenario why are you doing that.

Upvotes: 1

Rufus L
Rufus L

Reputation: 37050

One option would be to expose a public AddItem method that takes an int and adds it to your private field:

public void AddItem(int item)
{
    _s.Add(item);
}

Obviously you could also return the private field _s in the get method instead of a copy of it, and then clients could call Add directly on the private field through that reference, but then there's not much point in it being private. :)

Upvotes: 1

Related Questions