Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOutOfRangeException in indexed getter

In my indexed property I check whether the index is out of bounds or not. If it is, I throw an IndexOutOfBoundsException.

When I run the Code Analyst (in VS12) it complains with CA1065: Unexpected exception in unexpected location.

Referring to the description of CA1065, only

System.InvalidOperationException
System.NotSupportedException
System.ArgumentException
KeyNotFoundException

are allowed in an indexed getter.

Throwing IndexOutOfBoundsException seems natural to me, so what is the reasoning here? (And yes, I know I can turn the warning off, I just want to know the reasoning)

like image 558
Mario The Spoon Avatar asked Sep 02 '12 16:09

Mario The Spoon


People also ask

How do I resolve IndexOutOfRangeException?

Solutions to Prevent IndexOutOfRangeException Solution 1: Get the total number of elements in a collection and then check the upper bound of a collection is one less than its number of elements. Solution 2: Use the try catch blocks to catche the IndexOutOfRangeException .

What is IndexOutOfRangeException in C sharp?

An IndexOutOfRangeException exception is thrown when an invalid index is used to access a member of an array or a collection, or to read or write from a particular location in a buffer. This exception inherits from the Exception class but adds no unique members.

What are indexers in C#?

Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.

What error will occur if you try to access an address within an array that's above the upper bound or below 0?

You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException to be thrown.


1 Answers

A lot of classes use ArgumentOutOfRangeException for this, including List<T>. This is a subclass of ArgumentException so should satisfy the rule. I guess you could argue that for a vector etc accessed directly, there isn't actually a method call (it is a dedicated opcode - ldelem*), so the index in that case isn't actually an argument. Seems a weak argument, though.

like image 140
Marc Gravell Avatar answered Oct 12 '22 03:10

Marc Gravell