3

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?

Codor
  • 17,447
  • 9
  • 29
  • 56
Pranita Jain
  • 63
  • 1
  • 7

2 Answers2

5

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.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
  • syntactic sugar? what does that mean, can u please explain. – Pranita Jain Jul 08 '16 at 09:23
  • @PranitaJain In simple words i see syntactic sugar as syntax shortcuts provided by the compiler to make our life easier. While the compiler transforms that into a correct syntax. For example, you write `array.ToList();` the compiler changes it to `Enumerable.ToList(array);` (These are Extension methods by the way) – Zein Makki Jul 08 '16 at 09:28
2

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.

Codor
  • 17,447
  • 9
  • 29
  • 56