gcso
gcso

Reputation: 2345

How to calculate the size of a struct instance?

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.

Upvotes: 5

Views: 3339

Answers (4)

Georgi Stoyanov
Georgi Stoyanov

Reputation: 1218

You can use sizeof( Coordinate ) to calculate it progamatically, although this will require unsafe context. In your case the size is 16 bytes as you said. Properties do not count towards the size, since they are only wrappers. The size of a structure is simply the sum of the sizes of all its fields.

Upvotes: 1

user195488
user195488

Reputation:

First, to determine the size of your struct, use Marshal.SizeOf(struct) which returns the sum of the sizes of its members. Microsoft does recommend that the size of a struct be below 16 bytes, but it is really up to you. There is some overhead associated with structs. In case your struct has reference types as members, make sure you don't include the size of instances of reference types, just the size of the references.

Upvotes: 3

LukeH
LukeH

Reputation: 269278

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; }
}

Upvotes: 4

Mark Heath
Mark Heath

Reputation: 49482

You can find out the size using

System.Runtime.InteropServices.Marshal.SizeOf(new Coordinate());

Which returns 16. You are right - only fields count. You can add properties without increasing the size.

Upvotes: 1

Related Questions