dotnet / dotnet/dotnet-api-docs

Please add a remark to emphasise the potential weirdness with TKey being an enum and index 0

Open
#963 0 comments 0 reactions 0 assignees View on GitHub
area-System.Collections dotnet-api/prod Pri2 untriaged
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

Hi!
I just ran into a weird bug using a `KeyedCollection`.
Consider the following code
```
public class TestClass {
public TestKey TestKey;
}

public enum TestKey {
Entry1,
Entry2
}

public class TestKeyedCollection : KeyedCollection {
protected override TestKey GetKeyForItem(TestClass item) {
return item.TestKey;
}
}

public class Test {
public void RunTest() {
var collection = new TestKeyedCollection();
collection.Add(new TestClass() { TestKey = TestKey.Entry2 }); // Note that I add Entry2 first
collection.Add(new TestClass() { TestKey = TestKey.Entry1 });

var a = collection[0]; // would expect element at index 0, so Entry2
var b = collection[1]; // would expect element at index 1, so Entry1
}
}
```
But because of Ecma-334 5th Edition / December 2017 point "11.2.4 Implicit enumeration conversions" (http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf) `var a = collection[0]` in my setup implicitly converts to `TestKey.Entry1`, so for both `a` and `b` I get the same `TestClass` with `TestKey` being `Entry1`.

The result might be different on different runtimes, I only tried with Rider 2018.2.3. as IDE for a Unity 2018.1.6f1 project (and therefore some custom mono runtime), but nevertheless it would be very nice if you could add a comment to this documentation stating the potential issue when using an enum as TKey and trying to access the element at index 0.

Thank you very much!
Tim

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: 23e7fbba-ff7a-0770-a2c5-9fb11a830556
* Version Independent ID: f374f735-e1ad-b485-cfa9-e34c0c2b5655
* Content: [KeyedCollection<TKey,TItem> Class (System.Collections.ObjectModel)](https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.keyedcollection-2?view=netframework-4.7.2)
* Content Source: [xml/System.Collections.ObjectModel/KeyedCollection`2.xml](https://github.com/dotnet/dotnet-api-docs/blob/master/xml/System.Collections.ObjectModel/KeyedCollection`2.xml)
* Product: **dotnet-api**
* GitHub Login: @mairaw
* Microsoft Alias: **mairaw**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.