Lets say I have some known library to load data from an .xls file and returns a DataTable populated with data from the first sheet in any excel workbook. Also a Log function that prints out messages in the absence of a working debugger.
DataTable dtFoo = null;
DataTable dtBar = null;
DataTable dtChaz = null;
String[] files = new String[]{ "file1.xls", "file2.xls", "file2.xls" };
DataTable[] dts = new DataTable[] { dtFoo, dtBar, dtChaz };
for(int i = 0; i < 3; i++)
{
dts[i] = SomeLibrary.LoadFromFile(files[i]); //Returns a new DataTable
Log((dts[i] == null) + " " + dts[i].Rows.Count)
}
Log((dts[0] == null) + " " + (dtFoo == null));
Log((dts[1] == null) + " " + (dtBar == null));
Log((dts[2] == null) + " " + (dtChaz == null));
Log Output:
False 40
False 455
False 34
False True
False True
False True
Clearly I’m missing something important when working with reference type variables that I haven’t been able to figure out. Why are my DataTable variables still null after the loop completes?
This line:
… doesn’t alias the variables with the array elements, as you seem to think it does. It just creates a new array, and sets the initial values to the values of
dtFoo,dtBaranddtChazrespectively (all of which are null). The array and the variables are entirely separate afterwards.If you want to set the variables later, you’ll need:
Of course this doesn’t have to be with
DataTables. Simple example:Note that this is when you change the value of the array element. If instead you modify the object that the value refers to, that’s a different matter:
See my article on reference types and value types for more details. Basically you need to differentiate between references and the objects they refer to.