Gregg Bursey
Gregg Bursey

Reputation: 1217

Are C# data type sizes fixed or variable?

When referencing this article by Jon Skeet, I see that in C# an int would be 4 bytes of memory, and a struct like this:

struct PairOfInts
{
    public int a;
    public int b;
}

would be 8 bytes of memory total because:

The slot of memory is large enough to contain both integers (so it must be 8 bytes).

So if we had this:

public int a = 0;
public int b = 2147483647; //the max allowed for an int

Would both a and b still only take up 4 bytes of memory each? Would the same be true of a string? Example:

public string c = "";
public string d = "somethingreallyreallylong";

Upvotes: 2

Views: 542

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062770

There are two types in .NET that absolutely ignore the "fixed size" rule: string and arrays (int[], SomeType[,,], etc). Strings and arrays are allocated with a size appropriate to the declared contents at construction; once constructed, each instance is fixed size. All other types are fixed size.

Note that d is only the reference to the string, and the reference takes a fixed size. So: c and d are the same size even when there isn't a string: probably 8 bytes or 4 bytes depending on whethe you're running on 64-bit or 32-bit. The actual string object, however, will be whatever size it was allocated as when it was created to fit the contents.

Note that "fixed" doesn't mean "known and predictable ahead of time". For many types, the runtime / JIT decides the size based on the execution environment; IntPtr32, Vector<T>, etc - have sizes that can't be truly known in advance, but once known: are fixed for the duration of execution of an application. And even for many struct, the padding etc may be determined at runtime.

Upvotes: 3

Related Questions