Scott Kennedy
Scott Kennedy

Reputation: 29

When Do I use indexers, and how to know how to write them

// Indexer for the _accountList
public Account this[int index]
{
    get
    {
        if (index >= 0 && index < _accountList.Length)
            return _accountList[index];
        else
            throw new IndexOutOfRangeException("index is out of range");
    }
}

These are some notes I took, and is what we are covering, but after my research I am still hazy on this theory of when and how to use indexers.

My question is simply how and when to know to use an indexer? Is the only point of it to check to see if a statement is true? Where I can read up on indexers more in depth for beginners? And what does the exception on the last line mean?

throw new IndexOutOfRangeException("index is out of range");

What does the throw mean? I'm guessing it's stating that if it's not in range then to throw the new instance out of range. Seems cut and dry but when do I know when to use this exception?

Upvotes: 0

Views: 82

Answers (2)

Ry-
Ry-

Reputation: 224963

My question is simply how and when to know to use an indexer?

Use an indexer when it's convenient and when it makes sense in terms of acessing an object. For example, if you were implementing a custom list type, you would probably provide an indexer for convenient, clean, list-like access. If you were implementing a class that represents a process, you probably wouldn't implement an indexer, as a process is not obviously a collection of items.

Is the only point of it to check to see if a statement is true?

No. Not even close. The point is to get and/or set an item in a collection, specified by an index.

What does the throw mean? I'm guessing it's stating that if it's not in range then to throw the new instance out of range. Seems cut and dry but when do I know when to use this exception?

This has less to do with indexers and more to do with exceptions. If you haven't learned about exceptions yet, tackle this when you do. But it's just a boundary check, and it's not the only thing exceptions are used for.

Upvotes: 2

moribvndvs
moribvndvs

Reputation: 42497

Indexers are used as a shorthand way of accessing an element in a collection typically by index or key.

In your example, the indexer allows you to get the Account at the specified index. The logic checks to make sure the value of index is within the range of items in the collection.

So for example, if there are only 2 Accounts in the collection, and you ask for the Account at index 3, you are asking for an item that does not exist. Hence the IndexOutOfRangeException.

Upvotes: 1

Related Questions