Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C# implements integer type as a struct and not as a primitive type?

Tags:

c#

int

Looking on how the int type is implemented as the System.Int32 struct in C#, I wonder why was implemented like this (by wrapping this into a struct type), and not opted for a primitive type implementation like in Java?

Doesn't the additional wrapping in a struct produces additional performance hits?

like image 931
Tamas Ionut Avatar asked Nov 28 '16 13:11

Tamas Ionut


People also ask

Why C is the best language?

The programs that you write in C compile and execute much faster than those written in other languages. This is because it does not have garbage collection and other such additional processing overheads. Hence, the language is faster as compared to most other programming languages.

Why is C used?

C is a general-purpose programming language and can efficiently work on enterprise applications, games, graphics, and applications requiring calculations, etc. C language has a rich library which provides a number of built-in functions. It also offers dynamic memory allocation.

Why should you learn C?

C is very fast in terms of execution time. Programs written and compiled in C execute much faster than compared to any other programming language. C programming language is very fast in terms of execution as it does not have any additional processing overheads such as garbage collection or preventing memory leaks etc.

Why C language is named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


1 Answers

There is no "wrapping" in a struct going on here. For all practical purposes, System.Int32 struct is a built-in primitive type, in the sense that the compiler recognizes them, and generates special instructions while handling expressions of primitive types. The only place where an int (or any other struct for that matter) is wrapped is during a boxing conversion, which is required when you want to pass an int to an API that takes an object.

The biggest difference between Java's and C#'s handling of primitives is that you can use C# primitives in places where user-defined struct types can go, most notably, in C# generic arguments, while Java treats primitives as a completely separate group of types.

like image 78
Sergey Kalinichenko Avatar answered Nov 02 '22 06:11

Sergey Kalinichenko