简体   繁体   中英

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. eg

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

Like in above eg 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM