I’m building a app and I need to handle a position in a graph. This position have value of X, Y and the direction like north, east, south and weast. I think this position could be a Struct because its represent a single value in that graph.
I researched and thought about Structs and find these rules to use a Struct:
- It logically represents a single value, similar to primitive types
(integer, double, and so on). - It has an instance size smaller than 16 bytes.
- It is immutable.
- It will not have to be boxed frequently.
Here’s an example of my unfinished Struct:
public struct Position
{
public long PositionX { get; set; }
public long PositionY { get; set; }
public CompassPoint CompassPoint { get; set; }
}
public enum CompassPoint : byte
{
North,
East,
South,
West
}
I want to know how to calculate the size in bytes of my Struct and how I’ll know if it is immutable?
Thanks.
Update:
Okay. According to the responses it seems that my Struct passed the 16 bytes because only two long have 16 bytes + 1 byte of CompassPoint.
But an extra question would be: What I gained have using a Struct with 16 bytes and immutable? And look at DateTime Struct, it seems have more thatn 16 bytes? Any problem?
The size depends on what the
CompassPointtype is. However, eachlongwill use 8 bytes, so you are already over the recommended maximum of 16 bytes. It’s not a hard rule though, but you may get worse performance than if it was a class, depending on how you use it.The exact size of the struct is determined by the JIT compiler, but genreally you can just add the sizes of the members to predict the size. Small data types will be padded though, so if your
CompassPointuses just a single byte, it will still require 4 or 8 bytes to make the struct size reach an even boundary.The struct is not immutable, as you can change the properties in it. Make the setters private, and add a constructor that can create it to make it immutable: