10

This was really a question in my mind right from the point, where I started c# programming.

why int is struct type

enter image description here

And string is class type

enter image description here

Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60
  • 2
    First of all, please read what is the difference between `struct` and `class`. As a second, because `int` is `32-bit` which is perfect for `struct`. But you can't know how much `string` _can have_.. – Soner Gönül Jan 09 '14 at 13:34

2 Answers2

11

Because int has a fixed length, while string length is variable. Therefore, the compiler can reserve a fixed area for ints (mostly on the stack), and it must maintain a flexible buffer for a strings char array on the heap.

Thomas Weller
  • 11,631
  • 3
  • 26
  • 34
  • It would have been possible to make `String` be a value type if it e.g. contained a field of type `Char[]`. Such a design would have had the advantage of allowing `default(String)` to behave as an empty string [as was the case in the preceding COM framework] rather than a null value, but would have had the disadvantage of requiring boxing whenever a string was converted to `Object`. – supercat Jan 09 '14 at 17:43
4

int is a value type, and string is a reference type. Value types are passed by value (copied) when you pass them to a method or assign them to a new variable and so on. Reference types only have the reference copied.

Copying is fast for small objects like ints or floats, but at some point the cost of the copy operation becomes expensive, so a reference is preferable than copying the value all the time.

Although string is also immutable, like most value types (are there any mutable value types?) because strings can be quite large they are not a good candidate for passing by value.

Colin Mackay
  • 18,736
  • 7
  • 61
  • 88
  • 1
    Not entirely true. Because of its inherent dynamic nature regarding length, the compiler can't allocate a fixed size memory block for a string. – Thomas Weller Jan 09 '14 at 13:42
  • 1
    Yes, there can be mutable value types (you can define you own struct), but no, that's not a good idea. – Hans Kesting Jan 09 '14 at 13:59
  • 1
    @ThomasWeller: `String` could have been defined as a struct with a single private field holding a reference to an object of some variable-sized object e.g. `Char[]` which would never be modified. Such a design would have made it possible for `default(String)` to behave as an empty string rather than as a null value, which might have eased porting of code written for COM, which regarded an all-bits-zero pointer as a legitimate representation for an empty string. Conversion of such a string to `Object`, however, would have required either boxing or special Framework 'magic' to avoid boxing. – supercat Jan 09 '14 at 17:54