[C#] Best method for storing "temporary" data/fields

Joined
May 17, 2007
Messages
2,468
Reaction score
681
Hi

Been looking for an alternative for storing temporary data, things that will only be used for a matter of time, then never used again etc. A method I've been looking for for a while is the Dictionary collection type. But reading that it's slow when getting indexes etc, i cannot make up my mind if i should just stick to normal variables, or go to collection storage.

Field:
Code:
public Dictionary<string, object> TemporaryAttributes = new Dictionary<string, object>();

Adding data:
Code:
TemporaryAttributes.Add("LOGIN_STAGE", 0);

use:
Code:
If (TemporaryAttributes["LOGIN_STAGE"] == 0) return;
If (TemporaryAttributes["LOGIN_STAGE"] == 1) //do some shiet//

TemporaryAttributes.Remove("LOGIN_STAGE");
etc etc
instead of:
Code:
int loginStage = 0;
...
if (loginStage == 0) return;
if (loginStage == 1) //do some shiet here//

Good idea?
 
Give more information. What exactly is temporary data?
  1. How long does it need to last?
  2. What's the scope of the data? Method, class, global?
  3. Is it going to be accessed by multiple threads?
  4. How often will it need to be accessed?
  5. Why do you even want to change the way you store it?

Based on my assumptions
  1. It probably only needs to last until the end of the method.
  2. See above.
  3. Probably not.
  4. Probably not very often.
  5. A very good question, why do you want to change it?

Again, more information please.
 
An example of what i'll be using it for would be login.
It would be used in inside a method, then removed at the end of the message, yes.

A hashmap (dictionary<string, object>) is created for every player (initialized @ constructor)
in login method a temp attribute is created, called login stage, after usage, it's removed from the hashmap.

How often will it be used? it's created for each player login
No it wont be used by multiple threads, only one.
no i won't change the way i store it, but it will change values
not accessed much,
 
You're pretty well off using the dictionary., that is if you have a fair amount of "temporary data" you need to store. If it's really only two or three, using a dictionary might be a bit unnecessary, as creating a simple type to store the data might be a better alternative if you're just looking to cut down on the amount of variables contained in your class. If you're dealing with more than just a few (greater than say four or five), dictionary is probably the best choice.
 
Back