0

The below post was quite informative about the passing reference types. However, I now have a practical question of getting around this behaviour. I am passing a DataTable to a second window with the below code;

Window2.LoadedTblData = _loadedTblData;

Once this has been passed I would like the user to continue to be able to use Window1 (which means manipulating _loadedTblData) without impacting the data in Window2. I.e. I want to pass the table by value, not by reference. How would I do this?

Why is list when passed without ref to a function acting like passed with ref?

windowsgm
  • 1,566
  • 4
  • 23
  • 55
  • Just a correction of your terminology: you wouldn't say you want to "pass the table by value", rather you want to "pass a copy of the table". – Blorgbeard Oct 06 '17 at 16:09
  • 1
    Hence the question... – windowsgm Oct 06 '17 at 16:15
  • 2
    Your question is: how to create a copy of the DataTable so that no modifications in the copy are reflected back in the original. The question is posed using incorrect assumptions about value/reference type and pass by value/reference semantics. You should pose a separate question on it, if you want that answered – Vikhram Oct 06 '17 at 16:19
  • When I say "pass the table by value" I mean the table data. I think this is pretty clear in how I explain my intent. I understand that passing a table means passing a reference, but imo its pretty obvious this isn't my intent by saying "not by reference". In any case someone provided the answer I was hoping for so I don't believe a new question is required. – windowsgm Oct 09 '17 at 12:12

2 Answers2

3

It's because both windows have a reference to the same actual object instance.

You need to make a copy of the datatable and pass the copy off to the other window.

https://msdn.microsoft.com/en-us/library/system.data.datatable.copy(v=vs.110).aspx

mikelegg
  • 1,197
  • 6
  • 10
2

If you want to have a copy of both the structure AND data of the table in each window, then you'll need to use DataTable.Copy as opposed to DataTable.Clone.

More info on Copy here.

Matthew Snyder
  • 438
  • 2
  • 10