0

This is an example I have seen in the Effective C# book:

private BindingList<PayrollData> data; 
public IBindingList MyCollection 
{
get { return data; } 
}
public void UpdateData() 
{
// Unreliable operation might fail: 
var temp = UnreliableOperation();
// This operation will only happen if 
// UnreliableOperation does not throw an 
// exception. 
data = temp;
}

The author says this will work for value type and not for reference type. I couldn't understand what he meant.

I think I now understand: a collection is a ref type. consumers of "data field" won't remeber they a re holding a copy to the old storage on the heap. if "data" was value type - the consumers (other code that uses data) will remeber they are holding a deep copy of data and will ask for it again when need to update.

right ?

reevesy
  • 3,452
  • 1
  • 26
  • 23
Elad Benda
  • 35,076
  • 87
  • 265
  • 471

1 Answers1

0

The collection is a reference type, so other holding code onto that will see the old data.

Two possible solutions:

Instead of data = temp use data.Clear(); data.AddRange(temp) which will change the contents of the data field.

Or better delete the MyCollection property and make class implement IEnumerable. This results in much better encapsulation.

Christian Horsdal
  • 4,914
  • 23
  • 24
  • Your class would control access to the PayrollData entitely by implementing the logic that control enumeration. Hence you can control exactly when the data changes and what happens to ongoing iterations over your enumeration. – Christian Horsdal Aug 23 '11 at 22:05
  • Moreover you avoid situations where other does something like instance.MyCollection.Clear() which clear your data field of all items. – Christian Horsdal Aug 23 '11 at 22:07