c# “Index was outside the bounds of the array” on empty Array

  • A+

I get error

"'Index was outside the bounds of the array"

on this line string Open = array[0].ToString(); when array is empty.

I used "if" statement to see if it can be by-passed when array is empty.

However, why am I still getting this error? How can I by-pass/fix it?

if (array != null || array.Length != 0)                 {                     int c = array.Count();                     string Open = array[0].ToString(); <--- ERROR                 } 


You used the logical OR operator in your if statement. You should have used the AND operator &&.

OR will evaluate to true if any of the two conditions is true, so your if statement will be run as long as array is not null.

It should be:

if (array != null && array.Length != 0) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: