In C#, indexers provide a way to define the behavior of accessing and setting values in a class or struct using an indexer syntax similar to arrays. They allow you to access elements of a collection without explicitly exposing the underlying data structure, providing a more intuitive and flexible way to work with collections.
Indexers are particularly useful when you want to encapsulate how elements are stored and accessed within a class. This tutorial will guide you through understanding and implementing indexers in C#.
An indexer is defined using the this keyword followed by square brackets []. Inside the brackets, you specify one or more parameters that define how the element is indexed. The indexer can have a getter and/or a setter to retrieve or modify the value at the specified index.
Here's the basic syntax for defining an indexer:
public ElementType this[int index]
{
get { /* return the element at the specified index */ }
set { /* set the element at the specified index */ }
}
- `ElementType`: The type of the elements in the collection.
- `int index`: The parameter used to specify the position of the element.
## Examples
### Basic Indexer Example
Let's create a simple class that uses an indexer to access and modify elements in an array:
```csharp
public class SimpleList
{
private int[] items;
public SimpleList(int size)
{
items = new int[size];
}
public int this[int index]
{
get
{
if (index < 0 || index >= items.Length)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
return items[index];
}
set
{
if (index < 0 || index >= items.Length)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
items[index] = value;
}
}
public int Length => items.Length;
}
In this example, the `SimpleList` class encapsulates an array of integers. The indexer allows you to access and modify elements in the array using the syntax `simpleList[0]`.
### Using the Indexer
Here's how you can use the `SimpleList` class with its indexer:
```csharp
public class Program
{
public static void Main()
{
SimpleList list = new SimpleList(5);
// Setting values using the indexer
list[0] = 10;
list[1] = 20;
list[2] = 30;
// Getting values using the indexer
Console.WriteLine(list[0]); // Output: 10
Console.WriteLine(list[1]); // Output: 20
Console.WriteLine(list[2]); // Output: 30
// Attempting to access an out-of-range index will throw an exception
try
{
Console.WriteLine(list[5]);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message); // Output: Index is out of range.
}
}
}
### Multi-dimensional Indexer Example
Indexers can also be used for multi-dimensional collections. Here's an example with a 2D array:
```csharp
public class Matrix
{
private int[,] data;
public Matrix(int rows, int cols)
{
data = new int[rows, cols];
}
public int this[int row, int col]
{
get
{
if (row < 0 || row >= data.GetLength(0) || col < 0 || col >= data.GetLength(1))
throw new ArgumentOutOfRangeException("Index is out of range.");
return data[row, col];
}
set
{
if (row < 0 || row >= data.GetLength(0) || col < 0 || col >= data.GetLength(1))
throw new ArgumentOutOfRangeException("Index is out of range.");
data[row, col] = value;
}
}
public int Rows => data.GetLength(0);
public int Cols => data.GetLength(1);
}
Here's how you can use the Matrix class with its indexer:
public class Program
{
public static void Main()
{
Matrix matrix = new Matrix(3, 3);
// Setting values using the indexer
matrix[0, 0] = 1;
matrix[0, 1] = 2;
matrix[1, 0] = 3;
// Getting values using the indexer
Console.WriteLine(matrix[0, 0]); // Output: 1
Console.WriteLine(matrix[0, 1]); // Output: 2
Console.WriteLine(matrix[1, 0]); // Output: 3
// Attempting to access an out-of-range index will throw an exception
try
{
Console.WriteLine(matrix[3, 3]);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message); // Output: Index is out of range.
}
}
}
In the next section, we'll explore events in C#. Events allow objects to communicate with each other by sending notifications when something of interest occurs.
Stay tuned for more tutorials on object-oriented programming and advanced features in C#!