Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the size of a struct instance?

Tags:

c#

struct

This question is simply to satisfy my interest. Reading Choosing Between Classes and Structures the page says "It has an instance size smaller than 16 bytes.".

Given this simple immutable struct.

public struct Coordinate
{
    private readonly double _latitude;
    private readonly double _longitude;

    public Coordinate(double latitude, double longitude)
    {
        _latitude = latitude;
        _longitude = longitude;
    }

    public double Latitude
    {
        get { return _latitude; }
    }

    public double Longitude
    {
        get { return _longitude; }
    }
}

Do properties also count towards the 16 byte limit? Or do only fields count?

If the latter wouldn't using a struct fail the guidelines provided by Microsoft since a double is 8 bytes? Two doubles would be 16 bytes which is exactly 16 bytes and not less.

like image 673
gcso Avatar asked Feb 23 '23 17:02

gcso


1 Answers

Just the fields count.

So in this case you've got two 64-bit (8 byte) fields; you're just about within the bounds of your heuristic.

Note that if you use any auto-implemented properties then the compiler will create "hidden" fields to back those properties, so your overall sum should take those into account too.

For example, this struct also requires 16 bytes:

public struct Coordinate
{
    public Coordinate(double latitude, double longitude) : this()
    {
        Latitude = latitude;
        Longitude = longitude;
    }

    public double Latitude { get; private set; }
    public double Longitude { get; private set; }
}
like image 189
LukeH Avatar answered Feb 26 '23 08:02

LukeH