views:

52

answers:

2

The SqlDataReader class offers a method called GetValues. What I find curious about this method is that it takes an object[] as input and returns an int of the number of values copied into the array.

Any idea why the method was designed that way, rather than returning a new Array?

+2  A: 

According to the documentation:

You can pass an Object array that contains fewer than the number of columns contained in the resulting row. Only the amount of data the Object array holds is copied to the array. You can also pass an Object array whose length is more than the number of columns contained in the resulting row.

This allows the caller to be in complete control of the memory allocation and also control the number of columns requested easily.

Nick
fair enough, however why not pass in an integer as a limiting value and get back an object[] of that length.object[] myValues = sqlDataReader.GetValues(3);
Ralph Shillington
@Ralph: The key is that the caller controls the memory allocation. If the function returns an array, then it is the callee controlling memory use. One concrete example would be to reuse the same array for each row, rather than getting a new array for each row.
John Fisher
@John: I guess I'm expecting GetValues() to behave somewhat like Directory.GetFiles(pattern); You get an array of strings back. Now in this case they have no choice, since there's no way for the caller to know how many files the method would return, which technically is not so with the sqldatareader.
Ralph Shillington
+2  A: 

Just a guess, but by passing in an array, you can reuse the same array over and over. Creating an array takes time. Not a lot of time, but if you are iterating over millions of results it can be a measurable performance gain by reusing the same array. Creating a new array each time will also cause the GC more work then necessary.

Brian