#519 – Differences Between structs and classes
February 14, 2012 1 Comment
There are a number of differences between a struct and a class, including:
- A struct is a value type (instance created on the stack); a class is a reference type (instance created on the heap)
- A variable defined as a struct type contains the actual data in the struct; a variable defined as a class type references or points to the data stored in the instance of the class
- Memory for a struct is released when its variable goes out of scope; memory for a class instance is released when the object is garbage collected
- When a struct is assigned to a new variable, a copy is made (changes to the original are not reflected in the copy); when an instance of a class is assigned to a new variable, the new variable references the existing instance
- When a struct is passed to a method, a copy is made
When a struct is passed to a method, a copy is made,
unless a reference to it is passed using either the “ref” or “out” qualifiers.
public struct struct_type
{ public int x1; }
public void foo_77 (out struct_type p_a_struct)
{ p_a_struct.x1 = 77; }
public void foo_99 (ref struct_type p_a_struct)
{ p_a_struct.x1 = 99; }
struct_type struct_1;
foo_77 (out struct_1);
struct_type struct_2;
struct_2.x1 = 88;
foo_99 (ref struct_2);
// struct_1.x1 = 77
// struct_2.x1 = 99