Indexers in C# Language
Indexers are a fundamental and powerful feature in C# that allow you to access elements in a class or struct
using an array-like syntax. They provide a convenient way to encapsulate the internal representation of an object and provide controlled access to its elements. In this post, we’ll explore what indexers are, how to use them, and provide examples to illustrate their usage.Syntax of an Indexer
In C#, an indexer is defined using the this
keyword, followed by square brackets containing the index parameters. The getter and setter methods are defined just like the properties of a class. Here’s the basic syntax of an indexer:
public type this[indexType index]
{
get { /* return the value at index */ }
set { /* set the value at index */ }
}
Example of an Indexer
Let’s create a simple example to demonstrate the concept of indexers. We’ll create a class named ShoppingCart
to manage a list of items. The ShoppingCart
class will have an indexer to access items by their index, like an array.
class ShoppingCart
{
private List<string> items = new List<string>();
// Indexer
public string this[int index]
{
get
{
if (index >= 0 && index < items.Count)
{
return items[index];
}
else
{
return "Index out of range";
}
}
set
{
if (index >= 0 && index < items.Count)
{
items[index] = value;
}
else
{
Console.WriteLine("Index out of range");
}
}
}
public void AddItem(string item)
{
items.Add(item);
}
}
In this example, the ShoppingCart
class has an indexer that allows you to access items in the items
list using square brackets. The getter checks if the index is within the valid range and returns the item, or an error message if the index is out of range. The setter also checks the index range before setting the item.
Now, you can use this indexer to access items in a ShoppingCart
instance:
class Program
{
static void Main()
{
ShoppingCart cart = new ShoppingCart();
cart.AddItem("Item 1");
cart.AddItem("Item 2");
Console.WriteLine(cart[0]); // Output: Item 1
Console.WriteLine(cart[1]); // Output: Item 2
Console.WriteLine(cart[2]); // Output: Index out of range
cart[1] = "Updated Item 2";
Console.WriteLine(cart[1]); // Output: Updated Item 2
}
}
As you can see, the indexer provides a clean and convenient way to access and modify elements within the ShoppingCart
class.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.