Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `Dictionary<TKey, TValue>.KeyCollection` implement `IReadOnlyCollection` or not?

The question seems simple. Although the documentation says it does:

public sealed class KeyCollection : ICollection<TKey>, 
    IReadOnlyCollection<TKey>, IEnumerable<TKey>, ICollection, IEnumerable

the following code gives an error:

class MyKeys<T>
{
    readonly Dictionary<T, T> dict = new Dictionary<T, T> ();
    public IReadOnlyCollection<T> Keys { get { return dict.Keys; } set; }
}

saying that there is no conversion from KeyCollection<T> to IReadOnlyCollection<T>.

Moreover polish documentation (french too for that matter) says it does not:

[SerializableAttribute]
public sealed class KeyCollection : ICollection<TKey>, 
    IEnumerable<TKey>, ICollection, IEnumerable

Which is it?

And in case it's the error in english documentation, a bonus question:

Is there a way to get Keys as read-only collection?

like image 666
luk32 Avatar asked Jan 29 '15 15:01

luk32


People also ask

What is TKey and TValue?

In Dictionary<TKey,TValue> TKey is the type of the Key, and TValue is the Type of the Value. It is recommended that you use a similar naming convention if possible in your own generics when there is nore than one type parameter.

What is the use of Dictionary in c#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.

What is Dictionary in. net core?

Introduction. Dictionaries Dictionary<TKey, TValue> is used for storing a key-value pair. It is a generic collection that is defined in the System. Collection. Generic namespace and implements the IDictionary<TKey, TValue> interface.

How to create the Dictionary in c#?

You can create the Dictionary<TKey, TValue> object by passing the type of keys and values it can store. The following example shows how to create a dictionary and add key-value pairs. In the above example, numberNames is a Dictionary<int, string> type dictionary, so it can store int keys and string values.


1 Answers

Dictionary.KeyCollection does not currently implement IReadOnlyCollection.

However, the interface was added to the next version of .Net (v4.6). You can see that using VS 2015 preview.

You can also see that in this announcement (downloads an excel file with all the changes for v4.6)

like image 124
i3arnon Avatar answered Oct 12 '22 15:10

i3arnon