SoFunction
Updated on 2025-03-08

Detailed explanation of IReadOnlyDictionary and IReadOnlyList examples in C#

In C#IReadOnlyDictionaryandIReadOnlyListis an interface that represents read-only dictionary and read-only list. These interfaces provide read-only access to the collection, i.e. modifying the collection, such as adding, deleting, or modifying elements. This read-only feature is very useful for scenarios where data integrity is required or only read operations are required.

  • <TKey, TValue>:
    • The IReadOnlyDictionary<TKey, TValue> interface represents a read-only key-value pair dictionary. It inherits from the IEnumerable<KeyValuePair<TKey, TValue>> interface, so it can traverse key-value pairs in a read-only dictionary like it does.
    • IReadOnlyDictionary<TKey, TValue> provides a set of read-only properties and methods. For example, the Count property is used to obtain the number of key-value pairs in the dictionary, the Keys property is used to obtain a set of read-only keys, the Values ​​property is used to obtain a set of read-only values, the ContainsKey() method is used to check whether the dictionary contains the specified key, and the TryGetValue() method is used to obtain the corresponding value based on the key.
    • Example:
IReadOnlyDictionary&lt;string, int&gt; dictionary = new Dictionary&lt;string, int&gt;()
{
    { "Apple", 1 },
    { "Banana", 2 },
    { "Orange", 3 }
};
(dictionary["Apple"]);  // Output: 1// traverse the key-value pairs of read-only dictionariesforeach (var kvp in dictionary)
{
    ($"Key: {}, Value: {}");
}
  • <T>:
    • The IReadOnlyList<T> interface represents a list of read-only elements. It inherits from the IEnumerable<T> interface, so you can use an iterator to traverse the read-only list.
    • IReadOnlyList<T> provides a set of read-only attributes and methods. For example, the Count attribute is used to get the number of elements in a list, the Item[] attribute is used to access elements in a list through an index, the Contains() method is used to check whether the list contains the specified element, and the IndexOf() method is used to get the index position of the specified element in the list.
    • Example:
IReadOnlyList&lt;string&gt; list = new List&lt;string&gt;() { "Apple", "Banana", "Orange" };
(list[0]);  // Output: Apple// traverse the read-only listforeach (var item in list)
{
    (item);
}

It should be noted thatIReadOnlyDictionaryandIReadOnlyListThe interface only provides read-only access to the collection and does not allow modification operations to the collection. If you need to modify the collection, you can useDictionary<TKey, TValue>andList<T>kind.

This is all about this article about IReadOnlyDictionary and IReadOnlyList in C#. For more related contents of C# IReadOnlyDictionary and IReadOnlyList, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!