create a readonly dictionary in csharp

In C#, you can use the System.Collections.Generic namespace to create a readonly dictionary using the ReadOnlyDictionary<TKey, TValue> class.

Here's an example of how to create a readonly dictionary with string keys and int values:

main.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> dict = new Dictionary<string, int>
        {
            {"apple", 1},
            {"banana", 2},
            {"orange", 3}
        };

        // Create a readonly dictionary from the original dictionary
        ReadOnlyDictionary<string, int> readonlyDict = new ReadOnlyDictionary<string, int>(dict);

        Console.WriteLine("Readonly dictionary:");
        foreach (KeyValuePair<string, int> kvp in readonlyDict)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}
682 chars
26 lines

In this example, we first create a normal dictionary with some key-value pairs. Then we use the ReadOnlyDictionary<TKey, TValue> constructor to create a readonly dictionary from the original dictionary.

One thing to note is that the readonly dictionary is just a wrapper around the original dictionary, so any changes to the original dictionary will be reflected in the readonly dictionary.

gistlibby LogSnag