Wednesday, June 10, 2026

C# Example of Indexer in Generic class

Wrong Question: How can we decide whether an Indexer is generic -by looking at its index paramter or by looking at its return type? If paramter is generic type placeholder then generic or if return type is generic type placeholder then generic?

Right Answer: An indexer itself is not declared as "generic" in C#. Instead, an indexer can use generic type parameters that belong to its containing class or to the types used in its signature.

How do we identify that an indexer is using a generic type?

Look at both the parameter list and the value type (return type/get-set type). If any part of the indexer's signature uses a generic type parameter (T, TKey, TValue, etc.), then the indexer depends on a generic type parameter.

Case1. Generic type in the value type
public T this[int index]  // Generic because value type is T
{
    get; set;
}
Case2. Generic type in the index parameter
public string this[T key] // Generic because parameter type is T
{
    get; set;
}
Case3. Generic type in both places
public T this[T key] // Generic because both use T
{
    get; set;
}
The following code explains about Indexer in a Generic class:
public class Customer<T>
{
    private T Property1;
    private T Property2;
    public T this[int index]
    {
        get
        {
            if (index == 0)
                return Property1;
            else if (index == 1)
                return Property2;
            else
                throw new IndexOutOfRangeException();
        }
        set
        {
            if (index == 0)
                Property1 = value;
            else if (index == 1)
                Property2 = value;
            else
                throw new IndexOutOfRangeException();
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Customer<string> customer = new Customer<string>();
        customer[0] = "Ajeet";
        customer[1] = "Delhi";
        Console.WriteLine("Customer " + customer[0] + " lives in " + customer[1]);
        Customer<int> customerObj = new Customer<int>();
        customerObj[0] = 101;
        customerObj[1] = 20000;
        Console.WriteLine("Customer ID: " + customerObj[0] + " has Ordered the products of value: Rs." + customerObj[1]);
    }
}
OUTPUT
Customer Ajeet lives in Delhi
Customer ID: 101 has Ordered the products of value: Rs.20000

No comments:

Post a Comment

Hot Topics