tags:

views:

113

answers:

4

I have the following snippet of code:

public static List<string> sqlData = new List<string>();

//
//  lots of code here
//

if (/* check here to see if the sqlData[whatever] index exists  */)
{
    sqlData.Insert(count2, sqlformatted);
}
else
{
    sqlData.Insert(count2, sqlformatted + sqlData[count2]);
}

What I want to know is how to check the index on sqlData to see if it exists before trying to insert something that contains itself.

+3  A: 

If whatever is always positive then you can use this:

if (whatever < sqlData.Count) { ... }

Or if whatever could also be negative then you need to add a test for that too:

if (whatever >= 0 && whatever < sqlData.Count) { ... }
Mark Byers
When I go to use sqlData.Length, it Visual C# Express 2010 doesn't offer it as an option.
Claude
@Claude: Sorry that was an error. It's Count for lists (Length for arrays). I've updated my answer.
Mark Byers
@Abe Miessler: I think it should be OK. If the list is length 1, then 0 is the largest valid index.
Mark Byers
@Abe: Either `< sqlData.Count` or `<= sqlData.Count - 1` should be ok.
Nelson
Yes, this works fine. Thanks a lot :)
Claude
Ahh your right, missed that
Abe Miessler
+2  A: 

Check the length against the index:

sqlData.Count < count2
Abe Miessler
A: 
if(sqlData.Count > whatever )
{
 //index "whatever" exists
  string str = sqlData[whatever];

}
Arseny
A: 

If you mean check whether count2 is a valid index for sqlData

(count2 >= 0) && (count2 < sqlData.Count)

vc 74