This was really a question in my mind right from the point, where I started c#
programming.
why int
is struct
type
And string
is class
type
This was really a question in my mind right from the point, where I started c#
programming.
why int
is struct
type
And string
is class
type
Because int
has a fixed length, while string
length is variable. Therefore, the compiler can reserve a fixed area for int
s (mostly on the stack), and it must maintain a flexible buffer for a string
s char array on the heap.
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.