Question

I have added a new class to my library which will be part of the public documented API. The underlying data structure is a native array though List<T> is used when first generating the native array.

The MSDN indicates that List<T> throws ArgumentOutOfRangeException rather than IndexOutOfRangeException (which can be thrown when accessing a native array).

So I plan to update my functions to always throw ArgumentOutOfRangeException for consistency within my documented API like follows:

public class MyClass {
    private int[] _values;

    public int GetValue(int index) {
        if (index < 0 || index >= _values.Length)
            throw new ArgumentOutOfRangeException("index");
        return _values[index];
    }
}

My question is this:

Will the above source incur two range checks (my one + native array one) or is the .NET compiler smart enough to remove the IndexOutOfRangeException checks?

Was it helpful?

Solution

Why bother? I agree that it is odd that they don't use the same exception and perhaps even weirder that the text for ArgumentOutOfRangeException says that the index was out of range, but I don't see this adding a lot of value.

These exceptions usually indicate a program error that should be fixed. The exception should not be caught and "handled".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top