Claude
Claude

Reputation: 33

How do I check to see if a list index exists in C#?

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.

Upvotes: 3

Views: 15262

Answers (3)

Abe Miessler
Abe Miessler

Reputation: 85056

Check the length against the index:

sqlData.Count < count2

Upvotes: 4

Arseny
Arseny

Reputation: 7351

if(sqlData.Count > whatever )
{
 //index "whatever" exists
  string str = sqlData[whatever];

}

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838216

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) { ... }

Upvotes: 6

Related Questions