How are primitive data types made in C#?

How do System.float, System.int and other primitives types work? I never understood how it was possible to make primitives structs and I wonder if I could make my own numeric type.  


Solution 1:

Assuming we're talking about a C# compiler which targets the Common Language Infrastructure (CLI), as almost everything does, it basically uses the primitive types exposed by the CLI.

There are effectively three levels of support to consider:

  • Genuine primitives, with their own representation and instructions in IL
  • Numeric types that the C# compiler has special knowledge of, but which aren't part of the the CLI - basically, System.Decimal. This is also part of the Common Type System (CTS) which means that if you create a const decimal in C#, you can still consume it in VB, for example. But there's still no direct IL support.
  • Other numeric types, such as BigInteger - you can write your own ones of these.

The middle ground of the second bullet allows C# to have decimal literals and decimal constants, neither of which are possible for the third bullet. For example, BigInteger doesn't have language support, so you can't write:

// This isn't valid
BigInteger bigInteger = 123456789012345678901234567890;

You'd have to parse a string representation instead. Likewise you can't have a const BigInteger.

(In theory it would be possible to have a type with support in C# but not in the CTS. I don't know of any such types.)

Solution 2:

Primitive types like int and float are supported directly by the processor, and the .net platform and languages have similar built-in support for them. So there are no way you could create your own primitives at the language level.