#519 – Differences Between structs and classes

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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #519 – Differences Between structs and classes

  1. Ralph Burton says:

    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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: