How to work with read-only collections in C#


A collection represents a set of objects used for the storage and retrieval of data. Collections enable you to allocate memory dynamically to store elements and then retrieve them using a key or index as needed.

You can have standard or generic collections. While standard collections don’t provide type-safety, generic collections are type-safe. The standard collections are part of the System.Collections namespace, and the generic collections are part of the System.Collections.Generic namespace.

An immutable object is defined as an object that cannot be changed after it has been created. Not all collections are immutable, but you can use the read-only collection types in .NET Core such as IReadOnlyList, IReadOnlyDictionary, and IReadOnlyCollection to implement immutable types. These all are part of the System.Collections.Generic namespace.

This article discusses these read-only immutable collection types in .NET Core and how you can work with them in C#. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project in the subsequent sections of this article.

Copyright © 2021 IDG Communications, Inc.



Source link