Introduction
C# provides data structures that are read only. Interfaces such as IReadOnlyCollection
, IReadOnlyList
, and IReadOnlyDictionary
are examples of these data structures. In this blog post we will look at these three structures.
IReadOnlyCollection
IReadOnlyCollection
is the base of both IReadOnlyList
and IReadOnlyDictionary
. Suppose we have a list of users that we want to return as a ReadOnlyCollection, here’s how we go about it:
List<Users> users = new List<Users>()
{
new Users() { Id = 1, FirstName = "John", LastName = "Smith", Active = true },
new Users() { Id = 2, FirstName = "Donald", LastName = "Jameson", Active = false },
new Users() { Id = 3, FirstName = "Lilly", LastName = "Rose", Active = true },
};
IReadOnlyCollection<Users> allUsers = users;
IReadOnlyList
IReadOnlyList
is like IReadOnlyCollection
except IReadOnlyList
contains an index.
IReadOnlyList<People> students = gradStudents;
People fifthStudent = students[5];
IReadOnlyDictionary
IReadOnlyDictionary
as the name indicates is a read only dictionary, but allows access through keys, values, indices, the methods ContainsKey and TryGetValue.
Dictionary<int, Users> users = new Dictionary<int, Users>(){
{1, new Users() { Id = 1, FirstName = "John", LastName = "Smith", Active = true }},
{2, new Users() { Id = 2, FirstName = "Donald", LastName = "Jameson", Active = false }},
{3, new Users() { Id = 3, FirstName = "Lilly", LastName = "Rose", Active = true }}
};
IReadOnlyDictionary<int, Users> readOnlyUsers = users;
var firstUser = readOnlyUsers[0];
var usersKeys = readOnlyUsers.Keys;
var usersValues = readOnlyUsers.Values;
var SeventhUserExists = readOnlyUsers.ContainsKey(7);
Users someUser;
var SecondUserExists = readOnlyUsers.TryGetValue(2, out someUser);