incrementing an object array

sde

Well-known member
Joined
Aug 28, 2003
Messages
160
Location
us.ca.fullerton
im trying to create an array of objects without using a collection. [CS]public Object[] GetObjects(string Name)
{
Object[] objects = new Object[] { };

SqlConnection con = new SqlConnection(strCon);
con.Open();

string strSQL = "Select ID from table where Name LIKE%" + xID.ToString() + "%";

SqlCommand cmd = new SqlCommand(strSQL,con);
SqlDataReader reader = cmd.ExecuteReader();

int i = 0;

while(reader.Read())
{
objects = new Object( reader[0].ToString() );
i++;
}

return objects;
}[/CS]

Here is the exception:
Index was outside the bounds of the array. It gets triggered on the second Read() in the while loop.

How can I do this without pre-defining the size of the array?
 
There is no easy way around that, except to use a collection. Collections are recommended when the amount of the objects your going to use/allocate is unknown at runtime.

In your case, you could do 2 queries. 1 that does a SQL COUNT (*) to find out the # of ids that will be returned and thena second query 2 retrieve those values.

But what if, after the 1st query is returned and before the 2nd qeury is sent, more ids are added? Unless you use locking of sometype, you will only have more problems.

If you want to return an array of objects, just use the ToArray or CopyTo method
 
Back
Top