This code can throw a null pointer exception.
if (myArray[0] != null)
{
//Do Something
}
How can I test to make sure there is an element @ index 0?
Without throwing an exception when the array is empty.
This code can throw a null pointer exception.
if (myArray[0] != null)
{
//Do Something
}
How can I test to make sure there is an element @ index 0?
Without throwing an exception when the array is empty.
One small change I would make to Tim's answer is this:
if (myArray != null && myArray.Any() && myArray[0] != null)
{
//Do Something
}
.Any checks to see if there is at least 1 without having to iterate thru the entire collection. Also, this version works with any IList< T>-implemtor.
I understand that there might be a LINQ/IEnumerable-version of .IsNullOrEmpty in some future version of .NET which would be very handy here. Heck, you could implement it as an extension method yourself!
public static class MyExtensions
{
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
return (source == null || !source.Any());
}
}
Then your test becomes
if (!myArray.IsNullOrEmpty() && myArray[0] != null)
{
// ...
}
Length or Count of an array or list (most/all ICollections, really) is an O(1) operation, it does not require iterating through the entire collection. The LINQ Any() method you suggest is slightly slower than checking the Length or Count yourself, but could be preferable, especially since it works on any IEnumerable<T>.GetCount() method instead. Obviously, this isn't always true, but it's an assumption about what a property is, instead of assuming something about an interface.