Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class with indexer and property named "Item"

Tags:

c#

.net

indexer

Is it possible to create a class in .NET 4 with:

  1. an indexer,
  2. a property named "Item"?

For example, this C# class will not compile for me:

public class MyClass {     public object Item { get; set; }     public object this[string index] { get { return null; } set { } } } 

The compiler gives an error CS0102:

The type 'MyClass' already contains a definition for 'Item'

although I am only explicitly defining Item once.

like image 847
Michael Avatar asked Feb 24 '11 20:02

Michael


People also ask

Can a class have multiple indexers?

Like functions, Indexers can also be overloaded. In C#, we can have multiple indexers in a single class. To overload an indexer, declare it with multiple parameters and each parameter should have a different data type. Indexers are overloaded by passing 2 different types of parameters.

What is property and indexer in C#?

The new concept in C# it is an object that acts as an array. It is an object that is to be indexed as an array. Indexer modifier can be private, protected, public or internal. The return type can be any valid C# data types. Indexers in C# must have atleast one parameter.

What is the use of indexers in C#?

Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access as an array. The compiler will generate an Item property (or an alternatively named property if IndexerNameAttribute is present), and the appropriate accessor methods.

Does an indexer allows an object to be indexed?

Indexers enable objects to be indexed in a similar manner to arrays. A get accessor returns a value. A set accessor assigns a value. The this keyword is used to define the indexer.


2 Answers

Based on this site, it is possible to use an attribute to rename the Indexer

public class MyClass {     public object Item { get; set; }     [System.Runtime.CompilerServices.IndexerName("MyItem")]     public object this[string index] { get { return null; } set { } } } 
like image 70
Jack Bolding Avatar answered Oct 03 '22 01:10

Jack Bolding


C# internally creates a property called Item for languages that don't support the indexer. You can control this name using the IndexerNameAttribute, like this:

[IndexerName("MyIndexer")] public object this[string index] {     get { return blah; } } 
like image 31
Danny Tuppeny Avatar answered Oct 03 '22 00:10

Danny Tuppeny