Struct — RexDac Academy

RexDac AcademyTechnical notes · Some prior knowledge helps
0%Published notes read · this device

Level 4 — Classes

Struct

Original notes by SunDiaL · View English source

A struct is identical to a class, except it is a value type. 95% of the time you will use a class, so here's just how to define one and a table with the differences between them.

Defining a struct

struct ThisIsMyStructNameForRealz
{

}

Difference between class and struct

Characteristic Structs Classes
Type Value types, stored on the stack Reference types, stored on the heap with a reference on the stack
Memory Allocation Faster allocation/deallocation for small data structures Have overhead but offer more flexibility for complex objects
Inheritance Cannot inherit from other structs or classes (can only implement interfaces) Support inheritance, allowing for class hierarchies
Assignment Behavior Create a copy of all data when assigned to a new variable Copy only the reference; both variables point to the same object
Default Constructors Have implicit parameterless constructors that initialize fields to default values Require explicit parameterless constructors if needed
Best Used When Creating small, simple data structuresObject's lifetime is shortObject will not be modified after creationValue semantics (copying on assignment) is desiredMemory efficiency is critical Creating complex objects with behaviorsInheritance is neededObject needs reference semanticsObject will be modified after creationObject might be null
Examples Point coordinates, dates, colors, small mathematical objects Business entities, services, controllers, UI components