What is the difference between value type and reference type?
What is the difference between value type and reference type?
Value Types: Store data directly, allocated on the stack, copied on assignment.
Reference Types: Store references to data, allocated on the heap, shared between references.
Value Types:
Storage: Value types store the actual data directly in their own memory allocation.
Memory Allocation: They are typically stored on the stack, which makes allocation and deallocation faster.
Examples: Common value types include:
Primitive data types: int, float, char, bool, etc.
Structs in C#.
Behavior: When you assign a value type to another, a copy of the value is created. Changes to one do not affect the other.
Reference Types:
Storage: Reference types store a reference (or pointer) to the actual data, which is stored in the heap.
Memory Allocation: They are usually stored on the heap, which can lead to slower allocation and deallocation compared to stack-based storage.
Examples: Common reference types include:
Classes, arrays, strings, and delegates in C#.
Behavior: When you assign a reference type to another, both variables point to the same object. Changes to one will reflect in the other since they reference the same memory location.