Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why System.Int32 is struct and System.String is class [duplicate]

Tags:

c#

class

struct

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

like image 939
Nitin Varpe Avatar asked Jan 09 '14 13:01

Nitin Varpe


People also ask

Why is Int32 a struct C#?

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.

What does System Int32 mean?

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. .

Is string a class or struct?

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.

Can classes inherit from struct C#?

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.


2 Answers

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.

like image 180
Thomas Weller Avatar answered Nov 02 '22 07:11

Thomas Weller


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.

like image 38
Colin Mackay Avatar answered Nov 02 '22 07:11

Colin Mackay