Admiral Land Admiral Land - 3 months ago 10
C# Question

Refs uses in Constructors when collection updates?

I have constructor of some service:

public Ctor(List<Items> items)
{
_items = items;
}

public void Work()
{
if(_items.Count() > 5)
//do some work
}


Work
method will be called time by time.
So, if outside of the object I change
items
- what happens?
Will
_items.Count()
change?

Because at this current version i use this:

public void Work()
{
if(StaticClass.Items.Count() > 5)
//do some work
}


Where
StaticClass.Items
updates when outside items collection changes.
So, if i make this:

var service = new Constructor(StaticClass.Items);


And then I update
StaticClass.Items
elements -

Can I use actual
_items.Count()
value when
Work
method calls (by some timer) or should I use
ref
keyword?

Answer

When you pass a collection through the constructor like your example, you actually pass the reference of the list. ref keyword is, in most cases, for struct and value type parameters.

Doing this:

public myClass(IEnumerable<MyOtherClass> pMyItems)
{
    _items = pMyItems;
}

will be the same as

public myClass(ref IEnumerable<MyOtherClass> pMyItems)
{
    _items = pMyItems;
}

because IEnumerable or List, in your case, are usually references types.

So to answer your question: whether you use ref or no, in your situation, modifying the collection outside of the instanciated object will modify the collection in the instanciated object: it is the same instance, referenced at both places.

Here's the MSDN entry for the ref keyword in C# for more infos.

Comments