C # Is it possible to replace my dictionary class with the contents of a text file?

advertisements

For example, in a file of my project I have Dictionaries.cs containing:

 public DictionaryInit() {

        public Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
        {
            {180000, new DictionaryCheckup {theGrouping="H"}},
            {180001, new DictionaryCheckup {theGrouping="H"}},
            {180303, new DictionaryCheckup {theGrouping="H"}},
        };

     public Dictionary<int, DictionaryCheckup> C = new Dictionary<int, DictionaryCheckup>()
        {
            {180700, new DictionaryCheckup {theGrouping="C"}},
            {180201, new DictionaryCheckup {theGrouping="C"}},
            {180503, new DictionaryCheckup {theGrouping="C"}},
        };

      Etc.
     }

(DictionaryCheckup is a class that get;set; the string theGrouping)

The idea is that I wanted to allow my end user to hot swap a criteria, which is the dictionary class in question. Should he need to add a Dictionary U, he will simply need to copy the structure in the text file, replace the Key or Value where necessary, and then select it from the program. This loads it and replaces my dictionary class at runtime. Is this possible?

After some research, I found that Json and serialization is a method of doing this, but I'm not so familiar with it, or if there's any difference from reading a text file. Here is a thread I found: How do I read and write a C# string Dictionary to a file?.

In these examples, i'm not sure how they differentiate a key from a value. Furthermore, I don't think I will be able to access my DictionaryCheckup class through this, which is the criteria the Key is valued to.

So, my question is whether I can, for simplicity, write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime? Or would I have to create a var dictionary, and then add keys and values to it based on the external file? I'll probably look into the Json method anyway of seralization, I'm just worried about implementing a web function when my program has nothing to do with it.


how they differentiate a key from a value

From the format. If you try any of those steps, the resulting file clearly differentiate between the keys & values.

I don't think I will be able to access my DictionaryCheckup class through this

You will be able to. If you use JavaScriptSerializer, just make sure you follow the requirement, similar requirement exist for JSON.NET. Of course, the Linq to XML answer have to be modified if you have complex type.

write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime?

Yes, you can just deserialize the collection at once, no need to create the empty collection and fill it one by one. This is true for all serialization method.