Stact, heap, value types and reference types

todo

http://jacksondunstan.com/articles/3261

Structs

The choice of which to use depends on several factors. You might want a struct if:

  • The object only lives in a method
  • The object contains a small amount of data
  • The object is immutable
  • You want to avoid memory fragmentation
  • You need unmanaged blocks of memory
  • You need unions

However, there are several things to consider:

  • Avoid using reference types inside a struct; it promotes pointer chasing
  • Do not pass or return structs that are larger than ~16 bytes. For these, use ref or out in the method arguments
  • If you need to often change 1 or 2 fields inside your struct, then you probably want a class instead

Best Practice

Generally, to enforce the immutable nature of a struct, it is best practice to tag each field as readonly.

public struct Data
{
    public readonly int Thing1;
    public readonly float Thing2;
    public readonly Vector3 Thing3;
}

You'll also want to implement IEquatable, unless you're 100% sure that the struct won't be used in a HashTable, Dictionary, or won't be compared, ever. If you're not sure how to implement GetHashCode, see Detect Field Changes or the example below:

public struct Entity : IEquatable<Entity>
{
    public readonly uint Index;
    public readonly uint Generation;

    public bool Equals (Entity other)
    {
        return Index == other.Index;
    }

    public override int GetHashCode ()
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + Index.GetHashCode ();
            hash = hash * 23 + Generation.GetHashCode ();
            return hash;
        }
    }
}

results matching ""

    No results matching ""