Property "Item" with index

I read the answers of the class with the index and property named "Item" , but they do not explain why I can have a class with several indexers, they all create the Item property and get_Item / set_Item (of course, work well, since these are different overloads) but I cannot have an explicit Item property.

Consider the code:

 namespace Test { class Program { static void Main(string[] args) { } public int this[string val] { get { return 0; } set { } } public string this[int val] //this is valid { get { return string.Empty; } set { } } public int Item { get; set; } //this is not valid } } 

Four methods have been created for two indexes:

 Int32 get_Item(String val) Void set_Item(String val, Int32 value) String get_Item(Int32 val) Void set_Item(Int32 val, String value) 

I would expect my property to create

 Int32 get_Item() Void set_Item(Int32 value) 

These overloads are usually acceptable, but somehow the compiler won't let me create such a property.

Please note that I do not need a way to rename the indexer, etc., this is known - I need an explanation. This answer: https://stackoverflow.com/a/166958/ does not explain why I can have multiple indexers.

+6
source share
1 answer

For the same reason that the following will not compile:

 public class Test { public int Foo { get; set; } public void Foo() { return; } } 

The above results in the โ€œTest Typeโ€ already contain a definition for โ€œFoo.โ€ Although they can be implemented as the Foo () method and the get_Foo () method, naming is an implementation detail - at the language level, it is .Foo () and .Foo , and since not all languages โ€‹โ€‹support this, the compiler considers this an error.

Similarly, other languages โ€‹โ€‹may not support the indexer and property with the same name. So, although you indicate that this can be compiled as get_Item () and get_Item (Int32), CLR designers nevertheless decided not to allow this. Although the CLR can be designed this way, it may not be supported at the language level, so they decided to avoid such problems.

+4
source

Source: https://habr.com/ru/post/947739/


All Articles