Click here to Skip to main content
15,902,112 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
T[] str = new T[3];
        int count = 0;

        public void Add(T value)
        {
            if (count < 3)
            {
                str[count] = value;
                count++;
            }
        }

        public T this[int index]
        {
            get
            {
                return str[index];
            }
            set
            {
                str[index] = value;
            }
        }



I try the above program to get output successfully. but i want to know what is the purpose of index is using here. if remove the index property, i also get the same output. so what index acting here???
Posted
Comments
F-ES Sitecore 8-Oct-15 7:39am    
You're not using it which is why it makes no difference if it is there or not. The indexor you use in the "Add" method is using the indexor of T[], not the one you've written. The indexor you wrote will only be used if people use it on the instance of your class.

It's up to you what functionality you provide in your classes.
You did add the indexer to allow accessing some items through the means of index syntax, e.g.
C#
MyClass c = ...;
var item = c[2];
If you do not want to provide this Syntactic Sugar[^] in your class, leave it away.
Regards
Andi
 
Share this answer
 
v2
The indexing has nothing to do with the generics - it is only being used with the array you declared: str with is declared as an array of the generic type.

If you replace the "generics" in your code with a "standard" type:
C#
int[] str = new int[3];
int count = 0;
public void Add(int value)
{
    if (count < 3)
    {
        str[count] = value;
        count++;
    }
}
public int this[int index]
{
    get
    {
        return str[index];
    }
    set
    {
        str[index] = value;
    }
}
Then it's more obvious.
And that's what generics allow you do do: declare code that can be used for any type of data, while maintaining strong typing
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900