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
In C#, Int32 Struct represents 32-bit signed integer(also termed as int data type) starting from range -2,147,483,648 to +2,147,483,647. It also provides different types of method to perform various operations. You can perform the mathematical operation like addition, subtraction, multiplication, etc. on Int32 type.
Int32 is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 (which is represented by the Int32. MinValue constant) through positive 2,147,483,647 (which is represented by the Int32. MaxValue constant. .
Swift takes a different approach: strings are structs, and in fact come packed with functionality. Almost all of Swift's core types are implemented as structs, including strings, integers, arrays, dictionaries, and even Booleans.
Structs and inheritanceIt is not possible to inherit from a struct and a struct can't derive from any class. Similar to other types in . NET, struct is also derived from the class System.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With