C#’s type system

Published:

C# is a strongly-typed object-oriented language.  Many of the types will appear familiar, at first glance, to those who know C or C++, and most C expressions will behave similarly in C#, but the C# type-system is fundamentally different.

In my previous post I introduced C#’s integer types. In this post I’ll look at C#’s type system.

All C# types derive from the Common Type System (CTS) provided by the .NET framework, and are inherited from the System.Object (keyword object) class.  I’ll look into the object class in more detail later, but it means that all variables have some basic methods and properties.

Value Types
and Reference Types in the
CTS

The diagram shows the inheritance hierarchy of types in the CTS.

C# has two categories of types: value types and reference types.  Variables of value types directly contain their data, whereas variable of reference types store a reference to a memory location containing an object.  More details on the differences in a later post.

All value types are either struct types or enumeration types.  The types we would normally think of as base types in C or C++ are actually structs, and the keywords used to identify them are aliases for types in the .NET framework.

The basic value types in C#, known as simple types, are:

Type category Reserved
word
Aliased
type
Literal
suffix
Range of values
Integer
Types
Signed sbyteSystem.SByte-128 … 127
shortSystem.Int16-32,768 … 32,767
intSystem.Int32-2,147,483,648 … 2,147,483,647
longSystem.Int64L-9,223,372,036,854,775,808 … 9,223,372,036,854,775,807
Unsigned byteSystem.Byte0 … 255
ushortSystem.UInt160 … 65,535
uintSystem.UInt32U0 … 4,294,967,295
shortSystem.UInt64UL0 … 18,446,744,073,709,551,615
Floating point
types
floatSystem.SingleF+/-1.5 x 10-45 to 3.4 x 1038, 7-digit precision
doubleSystem.DoubleD+/-5.0 x 10-324 to 1.7 x 10308, 15-digit precision
decimalSystem.DecimalM+/-1.0 x 10-28 to 7.9 x 1028, 28-digit precision
charSystem.CharAny Unicode character (UTF-16)
boolSystem.Booleantrue or false

The keywords and type names in the table above can be used interchangeably, although as a matter of style it’s probably a good idea to keep to one or the other.

The suffices can be used to specify a numeric type when writing a literal number in the code.

That’s all I’ve got time for at the moment. I think I’ll get into the second exercise next time. See you then.