views:

120

answers:

3
int 72

It's a question in our discussion in a C# class. I said 2 bytes, others said it uses 32 bits or 4 bytes due to the integer type. Which is correct?

+8  A: 

You need to be a lot more specific. Are you wondering about:

  • the size of a variable in memory holding that value
  • the size of the MSIL to load that value into the IL stack so it can be used in an expression
  • the size of the MSIL to declare a local variable capable of holding the value
  • the size of the MSIL to declare a member variable capable of holding the value
  • the size of the machine language produced from the MSIL by the runtime
  • the size of the metadata and debug information associated with it
  • something else?

There are a lot of different "costs" associated with the appearance of an integer literal such as (int)72 appearing in a program. If it's part of a larger expression, simplification may occur at compile time such that the marginal runtime cost of the literal is nothing at all (except for the debugger to display the longer snippet of source code).

Ben Voigt
Ah, good point about syntax. Too tired right now, I downright overlooked that :|
Joey
A: 

How long is a piece of string?

It depends which processor architectrue you are running on (and possibly even which compiler you use). This page explains - and gives you your answer.

LeonixSolutions
Fortunately in the Common Type System specification an `int` is 32 bits on all architectures and compilers.
Brian Gideon
+2  A: 

In most cases it will consume 4 bytes on the stack. That is because int is the C# keyword that maps to Int32 in the Common Type System (CTS).

Things get a little more complicated if it has to be boxed. See this article for an explanation on boxing. The boxed value would actually consume 12 bytes (at least on a 32bit system) on the heap; 4 for the actual data, 4 for the syncblock, and 4 the type handle or method table.

So the question isn't quite that simple.

Brian Gideon