1

Assuming we have a simple Person class:

public Person this[int index]
{
get { return (Person)arPeople[index]; }
set { arPeople.Insert(index, value); }
}

Let’s assume i have an array with N Person objects. If I try accessing non-existing index (N+1 for example), Should I throw exception in this case or return null? What are the considerations in this case?

Thanks in advance…

cadrell0
  • 17,109
  • 5
  • 51
  • 69
  • What does `arPeople` when accessing out of range index? In most cases, indexers throw an exception when the index is not found (see `Dictionary`, `List`, ...). – Cédric Bignon Jul 22 '13 at 13:21
  • 4
    Arrays do not hesitate to throw `IndexOutOfRangeException`, why should you? – Andrei Jul 22 '13 at 13:22
  • You are right guys, read the post, Thanks :) –  Jul 22 '13 at 13:24
  • I can think of one data structure, where you wouldn't want an `IndexOutOfRangeException`: a Ring buffer. For instance: a ring with 10 elements will return the first element if you try to access element `0`, `10`, `20`, etc., or the second element if you ask for `1`, `11`, `21`, etc., and so on. It *may* be useful. I don't know if such a data structure exists, though, since it's pretty easy to implement: `ring[i % ring.Count]` – Nolonar Jul 22 '13 at 13:37
  • @Nolonar, in that case, the element at index 1521 exists. So, there is no reason to return null or to throw an exception. – Cédric Bignon Jul 22 '13 at 13:42
  • Microsoft recommends NOT throwing exceptions in several places and has encapsulated this in [Rule CA1065](https://learn.microsoft.com/en-us/visualstudio/code-quality/ca1065?view=vs-2019). This rule includes getters of properties and indexers. They say this: "Properties are basically smart fields. Therefore, they should behave like a field as much as possible. Fields don't throw exceptions and neither should properties." (I would have made this an answer, but the question has been closed. This question is not the same as the 'already answered here' question the closer refers to). – Steve Lautenschlager Nov 03 '19 at 00:01

1 Answers1

2

Well, it depends on what is "expected" behavior and if you can recover from the error. In this case, you are the one that decides if returning null is a valid return value. Most often, collection indexers should throw an ArgumentOutOfRangeException when the index is not valid.

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81