Reputation: 11
Can anyone explain me how C# dictionary stored in memory? I do know that in C# memory management is done using heap and stack. But I really couldn't find a simple explanation on how memory is allocated when dictionary variable is created, is it created in stack frame or heap space?
Upvotes: 0
Views: 2510
Reputation: 190
You can always check the Reference Source to see most of .NET implementations:
All of the entries in the Dictionary are structs for example, so, they are going to be handled like ones:
private struct Entry {
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
Upvotes: 3
Reputation: 1062895
Firstly, you need to be very clear about what you're asking here; do you mean the dictionary? or the variable? because they're two completely different things.
The dictionary is an object on the managed heap.
The variable (the reference to the object on the managed heap) - could mean a "local", a "parameter", or a "field". Fields are wherever they are, and depends on the thing having the field (reference-type, vs non-boxed value-type (which may or may not itself be a field on something), vs boxed value-type). Could be heap or stack. Parameters and locals are usually on the stack, except when they are captured into a state context (async methods, anonymous methods / lambdas, iterator blocks, local functions), in which case they are actually treated as fields; and the "fields on what" depends on the exact context (local functions are structs, for example). Also note that the stack is an implementation detail!
But you probably mean "the dictionary itself", in which case: managed heap.
Upvotes: 4