Stack and Heap
-
HI, My question is,What is Stack and Heap in C#??? As i search in net also,but i didn't understand it clearly? So,can anyone explain me with simple example? Thanks...
-
HI, My question is,What is Stack and Heap in C#??? As i search in net also,but i didn't understand it clearly? So,can anyone explain me with simple example? Thanks...
-
HI, My question is,What is Stack and Heap in C#??? As i search in net also,but i didn't understand it clearly? So,can anyone explain me with simple example? Thanks...
Not really, no... it's a complicated subject. The first thing you need to get sorted is the difference between a variable, a reference, and an instance - because without that, none of the rest of this will make any sense. An
instance
is an example of a class. Thinking about cars, an instance is a car you can physically get into and drive - it is distinct from all other cars in that it will have a different registration / licence number, may be a different colour, may have a different owner. Each physical car is a different instance of a generic subject "A Car". Areference
is a "pointer" to an instance: "my car" is a reference to a physical vehicle, "your car" is a reference to a different one. "This car" could refer to the same vehicle as "my car" now, and to "your car" in a moment as we physically move from one to another. Clearly, you can have many references to the same instance! Avariable
is a named "place" that holds a value - this could be a number like 12 or 14, or a reference to an instance. So when we say:Car myCar = new Car("Mercedes", "A160", Color.Red);
We declare a
variable
calledmyCar
which holds areference
to aninstance
which is created via thenew
keyword. Avariable
doesn't have to hold areference
: it can hold avalue
instead:int i = 666;
We create a
variable
calledi
which contains thevalue
666 This is important, because we have different names for each type of variable: we call the first one areference type
and the second avalue type
and how they behave is different. -- We'll get tostack
andheap
soon, honest! -- When you copy a variable, it's important to know if it's a reference type or value type, because they seem to behave very differently:int i = 666;
int j = i;
i = i + 1;
Console.WriteLine("{0}:{1}", i, j);You expect to get "667:666" because if you didn't, then doing any kind of math would get very difficult! And you do: i and j are value types, so the value in i is copied into j, and then incremented - that doesn't affect the value in j because it's a copy of the value. If you think about variables as "pockets" it makes sense: you have five pennies in your right trouser pocket, and you copy the value to your left trouser pocket - you now have five coins in each pock