Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const Dictionary in c#

I have a class in C# that contains a Dictionary, which I want to create and ensure nothing as added, edited or removed from this dictionary as long as the class which contains it exists.

readonly doesn't really help, once I tested and saw that I can add items after. Just for instance, I created an example:

public class DictContainer
{
    private readonly Dictionary<int, int> myDictionary;

    public DictContainer()
    {
        myDictionary = GetDictionary();
    }

    private Dictionary<int, int> GetDictionary()
    {
        Dictionary<int, int> myDictionary = new Dictionary<int, int>();

        myDictionary.Add(1, 2);
        myDictionary.Add(2, 4);
        myDictionary.Add(3, 6);

        return myDictionary;
    }

    public void Add(int key, int value)
    {
        myDictionary.Add(key, value);
    }

}

I want the Add method not to work. If possible, I want it not to even compile. Any suggestions?

Actually, I'm worried for it is code that will be open for a lot of people to change. So, even if I hide the Add method, it will be possible for someone to "innocently" create a method which add a key, or remove another. I want people to look and know they shouldn't change the dictionary in any ways. Just like I have with a const variable.

like image 447
Samuel Carrijo Avatar asked May 12 '09 16:05

Samuel Carrijo


People also ask

Is there a dictionary in C?

Section 6.6 of The C Programming Language presents a simple dictionary (hashtable) data structure. I don't think a useful dictionary implementation could get any simpler than this. For your convenience, I reproduce the code here. Note that if the hashes of two strings collide, it may lead to an O(n) lookup time.


2 Answers

Hide the Dictionary totally. Just provide a get method on the DictContainer class that retrieves items from the dictionary.

public class DictContainer
{
    private readonly Dictionary<int, int> myDictionary;

    public DictContainer()
    {
        myDictionary = GetDictionary();
    }

    private Dictionary<int, int> GetDictionary()
    {
        Dictionary<int, int> myDictionary = new Dictionary<int, int>();

        myDictionary.Add(1, 2);
        myDictionary.Add(2, 4);
        myDictionary.Add(3, 6);

        return myDictionary;
    }

    public this[int key]
    {
        return myDictionary[key];
    }
}
like image 157
Neil Barnwell Avatar answered Sep 27 '22 21:09

Neil Barnwell


Don't define the Add Method.

Keep the myDictionary variable private and expose a Getter/Indexer so that it can only be read from outside that class..

like image 31
Eoin Campbell Avatar answered Sep 27 '22 19:09

Eoin Campbell