Here's the thing:
object[] arrayText = new object[1];
if (arrayText[1] == null)
{
MessageBox.Show("Is null");
}
We know that is going to be null, but it throws an exception, but I don't want to handle it in a try/catch block because that is nested in a loop and try/catch will slow it down, also it doesn't look really good:
object[] arrayText = new object[1];
try
{
if (arrayText[1] == null)
{
}
}
catch (Exception ex)
{
MessageBox.Show("Is null");
}
Thanks for you suggestions!
To check if an array is null, use equal to operator and check if array is equal to the value null. In the following example, we will initialize an integer array with null. And then use equal to comparison operator in an If Else statement to check if array is null. The array is empty.
The value of an index for an array element is never null. If an expression specifies a value for an index, and the expression evaluates to the null value, the null value is returned for the array value.
If the length of the object is 0, then the array is considered to be empty and the function will return TRUE.
Use array::empty() method to check if the array is empty: Instead, it examines if an array is blank or not, that is, if maybe the array's size is zero. If the size of the array becomes zero, this returns 1 which means true. Otherwise, this returns 0 which means false.
null
is not the problem here, but the index is invalid. Arrays in C# are 0-based, so if you create an array with 1 element, only index 0
is valid:
array[0] == null
You can avoid that by checking the bounds manually before accessing the index:
if (index < array.Length) {
// access array[index] here
} else {
// no exception, this is the "invalid" case
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With