Diskdrive
Diskdrive

Reputation: 18865

How to calculate how big a struct or class is?

I've been told I should only use structs when they are less than 16 bytes. If bigger, it would be more optimal to use a class.

I was wondering, how do I work that out?

Do I just add up all of the fields that are in the struct?

For example, if this struct

public struct Struct1
{
    int int1;
}

Then given it's got one integer and one int is 32 bits, is it then four bytes?

What about if I have lots of methods in this struct though? Would the method add to the size of the struct?

Upvotes: 3

Views: 1852

Answers (5)

Hannesh
Hannesh

Reputation: 7488

Only non-static variables use up space, methods don't. For example, your struct that you made there is four bytes big, because it is the size of an int.

You can also calculate the size using Marshal.SizeOf(GetType((Struct1)).

Unless you have memory critical applications, or have some special reasons you need a struct, I would suggest always using a class.

Upvotes: 3

Grant Thomas
Grant Thomas

Reputation: 45058

Make this analysis, and further, the decision, based on any such conclusion at design-time - not runtime, since you can't change the type definition at that point.

In order for you to work out the sizes, I'll just point you forward to a very interesting article (from 2005 MSDN magazine, but still relevant) which discusses the allocation of objects in the CLR, with reference to sizes, offsets et cetera; this will educate you more than enough to be able to determine what you need and also enable you to research further into what you're still unsure of:

http://msdn.microsoft.com/en-us/magazine/cc163791.aspx

Upvotes: 0

Kamran Khan
Kamran Khan

Reputation: 9986

Your best bet: When should I use a struct instead of a class?

MSDN has the answer: Choosing Between Classes and Structures. Do not define a structure unless the type has all of the following characteristics:

    * 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.

Upvotes: 0

Frederik Gheysels
Frederik Gheysels

Reputation: 56984

I would not solely think about the 16bytes limit when deciding whether to use a class or struct. I would look at the semantics first. If you need to create an entity, I would use a class. If you need to create a value type, I would first think of a struct.

Upvotes: 0

Massif
Massif

Reputation: 4433

Use the built-in sizeof keyword.

EDIT: Nevermind, only available when dealing with unsafe code. (also, only really useful then too)

Upvotes: 2

Related Questions