Null reference index #4851
-
Return null if index is out of range: If array has no element at index zero it will return null. It will work with reference types but could be expanded to value type if statement will return nullable: Same could be done with ranges. If range exceeds array length it will return null: This should help with situations when array is not null but index is out of range. With null-coalescing assignment this could be powerful tool for one line statements such as this one: Using older syntax this could be achieved only with if-else statement. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
I can't remember the last time I needed to put a guard statement around an array access to prevent out of bounds access and to provide a default value. In my experience, attempting to access an out of bounds value in an array is virtually certain evidence of a bug. The remedy is to fix the bug, not to mask the problem by patching around the array index. For the vanishingly small number of situations where this is desirable behaviour, a trivial extension method does what you want: public static T? Index<T>(this T[] arr, int index)
=> index < arr.Length ? arr[index] : default(T); Note that it doesn't need to use an if-else statement ... and it will work with any array. |
Beta Was this translation helpful? Give feedback.
-
There's already a method for this: var b = array1.ElementAtOrDefault(10); Yes you could argue it's a bit longer than |
Beta Was this translation helpful? Give feedback.
-
I have a TryGet extension method for arrays that lets me treat them kind of like a dictionary. |
Beta Was this translation helpful? Give feedback.
There's already a method for this:
Enumerable.ElementAtOrDefault
.Yes you could argue it's a bit longer than
?
, but 1) It already exists, 2) It doesn't normally need to be used very often, and 3) It stands out as being something unusual.