Structs

What?

A struct is essentially a small class which is stored on the stack rather than the heap.

Why?

The benefits of a struct is that they have less overhead than a class which makes them more efficient, there are some key things to take into account when deciding if you should use a struct rather than a class:

  • Represent a single value logically
  • Has an instance size that is less than 16 bytes
  • Is not frequently changed after creation
  • Is not cast to a reference type (Casting is the process of converting between types)

How?

public struct Employee
{
    private string firstName;
    private string lastName;
    private int employeeID;

    public Employee(string firstName, string lastName, int employeeID)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.employeeID = employeeID;
    }

    public override string ToString()
    {
        string fullName = this.firstName + " " + this.lastName;
        return fullName + ", Employee ID: " + employeeID;
    }
}