10

How much memory in bytes do types like int, bool, float, double, decimal, object, and string use when added as a field to an instance of a class?

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
user1306322
  • 8,561
  • 18
  • 61
  • 122
  • 1
    that depends on several things like .NET version and bitness (32 versus 64 bits)... the exact memory layout is usually unknown before runtime! For approximate figure you can check [MSDN](http://msdn.microsoft.com/en-us/library/eahchzkf%28v=vs.100%29.aspx). – Yahia Nov 12 '12 at 20:27
  • @Yahia actually 32bit vs 64bit does not matter. Byte will be byte, Int32 will be Int32 etc – John Demetriou Aug 08 '17 at 07:05
  • @JohnDemetriou do you have a source to back up your claim? – user1306322 Aug 10 '17 at 00:20
  • 1
    @user1306322 sure, let me find it :) but I am talking c# specifically, just to be clear as for the link https://msdn.microsoft.com/en-us/library/ms228360(v=vs.90).aspx an Int32 explicitly means 32 bits of width, regardless of system. Calling it int is just a shorthand (or sugar-coating) Also a Q&A from SO https://stackoverflow.com/questions/164643/is-an-int-a-64-bit-integer-in-64-bit-c – John Demetriou Aug 10 '17 at 12:31
  • Oh, that's what you meant. I thought you meant they take up different amounts of ram depending on the target platform bitness. – user1306322 Aug 10 '17 at 16:04

1 Answers1

14

This page shows the size of each datatype in bits (divide by 8 to get bytes):

byte 8
sbyte 8
int 32
uint 32
short 16
ushort 16
etc...

Object and string are reference types. Reference types take up at least the size of all the fields they contain plus the size of the reference itself.

Related

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452