Pranita Jain
Pranita Jain

Reputation: 73

Item property in c#

Is item property in c# is always used like indexer in c#? Let me explain with an example. ArrayList is having many properties like count,capacity, and one of them is Item.Item Property unlike count and capacity which are accessed by putting dot after name of ArrayList ,is not used by keyword Item but directly by Indexer. e.g.

ArrayList MyList = new ArrayList();
MyList.add(100);
MyList[0] = 200;

Like in above e.g. uses the Item keyword to define the indexers instead of implementing the Item property.

My Query : Can i say whenever in c# Item property is explained it should be implicitly understood that it's referring Indexer in term?

Upvotes: 4

Views: 5969

Answers (2)

Zein Makki
Zein Makki

Reputation: 30022

MyList[0] is an indexer, it makes you access the object like an array. Definition syntax is like this:

public T this[int index]
{
   // reduced for simplicity
   set { internalArray[index] = value; }
   get { return internalArray[index]; }
}

The compiler generate methods:

public T get_Item(inde index)
{
    return internalArray[index];
}

and

public void set_Item(inde index, T value)
{
    internalArray[index] = value;
}

There is no relation between List.Add(something) and List[0] = something. The first is a method that appends a values to the end of the list. The second is a syntactic sugar that calls a method List.set_Item(0, something).

Unless the [] syntax is directly supported by the CLR (as is array), then it is an indexer defined inside the class that uses syntactic sugar as explained above.

Upvotes: 5

Codor
Codor

Reputation: 17605

According to the documentation above, the indexer is defined as follows.

public virtual object this[
    int index
] { get; set; }

More precisely, there is actually no Item property, but the indexer is termed as 'Item property' in the documentation.

Upvotes: 2

Related Questions