I have a website that holds a dictionary of data sets. When a user changes pages, and I call the dictionary via its key, I always have to re add all the data sets to the dictionary. It seems kind of redundant. Is there a better way?
classA
public IDictionary<string, DataSet> DataDic { get; private set; }
classB
classA da = new classA();
da.DataDic.Add("Key1",".......");
da.DataDic.Add("Key2",".......");
da.DataDic.Add("Key3",".......");
This is what’s causing it:
If you instantiate an entirely new object every time then of course you’re going to have to re-populate that object every time.
Where do you get the data that you use to populate the object? Does that data change?
If the data is static, a quick and easy thing to try is to make the field static:
Then you just set it once and it will retain that data. Note that setting it is slightly different. You wouldn’t call an instance of the class, you’d call the class type itself:
This may be a significant design change, depending on how this data is fetched/used/etc. So there could be downsides that we don’t see within the context of this question.
Another option is to keep it the way it is, but re-factor the populating of the data into the object’s constructor:
This outwardly retains the structure of the class, just moves the populating of the data to a single place in code. Note, however, that the data is still being re-populated with each new instance of the class. So if getting the data in the first place is a heavy process and shouldn’t happen more than once, then you might not want to go with this approach.
There are pros and cons any way you look at it. And a lot of it has to do with factors outside the context of this question.
(Side note: Notice that I changed the case of your class in this code to begin with a capital letter. This is an idiomatic standard in C#. Note that the code syntax highlighter on this page didn’t highlight your class names as class names. The standard for C# is to expect classes to be capitalized.)