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?
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With