C# Type System
The C# type system is a unified type system that underlies all C# code. In the C# type system, all types, whether they are value types or reference types, derive from the ultimate base class System.Object
. This provides a unified model where all values can be treated as objects.
Value Types vs. Reference Types
C# distinguishes between two fundamental categories of types:
- Value Types: Directly contain their data. Examples include primitive types like
int
,float
,bool
, as well asstruct
andenum
types. When you assign a value type variable to another, the value is copied. - Reference Types: Store a reference (or pointer) to the actual data, which is located on the heap. Examples include
class
types,string
, arrays, and delegates. When you assign a reference type variable to another, only the reference is copied, meaning both variables point to the same object.
Key Type Categories
Primitive Types
C# provides a set of built-in primitive data types. These are value types and include:
Type | Description | Size (bits) |
---|---|---|
sbyte |
8-bit signed integer | 8 |
byte |
8-bit unsigned integer | 8 |
short |
16-bit signed integer | 16 |
ushort |
16-bit unsigned integer | 16 |
int |
32-bit signed integer | 32 |
uint |
32-bit unsigned integer | 32 |
long |
64-bit signed integer | 64 |
ulong |
64-bit unsigned integer | 64 |
float |
Single-precision floating-point | 32 |
double |
Double-precision floating-point | 64 |
decimal |
128-bit precise decimal for financial calculations | 128 |
char |
16-bit Unicode character | 16 |
bool |
Boolean (true or false ) |
Implementation dependent |
Reference Types
Reference types include classes, interfaces, arrays, delegates, and the built-in string
type.
- Classes: Define the structure and behavior of objects.
- Interfaces: Define contracts that classes can implement.
- Arrays: Store collections of elements of the same type.
- Delegates: Type-safe function pointers.
- String: An immutable sequence of Unicode characters.
Nullable Types
C# supports nullable value types, denoted by appending a question mark (?
) to a value type (e.g., int?
, bool?
). These allow a value type to hold a null value in addition to its normal range of values.
Generics
Generics provide a way to create types that can work with any other type while maintaining type safety. This is achieved through generic classes, interfaces, methods, and delegates.
For a more in-depth understanding of each type category, please refer to the linked sections in the navigation pane.
Learn more: