Possible Duplicate:
Fields of class, are they stored in the stack or heap?
If I have
Class A
{
int k=0;
}
and I'm doing:
A x = new A();
where is k
stored? On the heap or the stack? And why?
While value types are stored generally in the stack, reference types are stored in the managed heap. A value type derives from System. ValueType and contains the data inside its own memory allocation. In other words, variables or objects or value types have their own copy of the data.
Valid types are float and double . Even though there are many numeric types in C#, the most used for numbers are int (for whole numbers) and double (for floating point numbers).
Structs are value types, while classes are reference types, and the runtime deals with the two in different ways. When a value-type instance is created, a single space in memory is allocated to store the value. Primitive types such as int, float, bool and char are also value types, and work in the same way.
Value types include the following: All numeric data types. Boolean , Char , and Date. All structures, even if their members are reference types.
Even though k
is an int which is a value type it is contained in a reference type, so it will be stored on the heap as part of the memory allocated for x
- while this is an implementation detail, this is the current behavior of .NET.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With