Value Types
Value types are data types that hold their data directly. They are stored in the stack (or inline in a containing type) and are copied on assignment.
In C#, the following are considered value types:
- Built‑in numeric types (
int
,double
, ...) bool
,char
,byte
,short
,long
,float
,decimal
- Structs (
struct
) - Enumerations (
enum
) - Nullable value types (
int?
)
Why use value types?
Value types provide performance benefits in many scenarios because they avoid heap allocation and garbage‑collection overhead. They're ideal for small, immutable data structures.
Common Value Types
Type | Alias | Size | Range |
---|---|---|---|
System.Boolean | bool | 1 bit | True/False |
System.Byte | byte | 8 bits | 0 to 255 |
System.SByte | sbyte | 8 bits | -128 to 127 |
System.Int16 | short | 16 bits | -32,768 to 32,767 |
System.UInt16 | ushort | 16 bits | 0 to 65,535 |
System.Int32 | int | 32 bits | -2,147,483,648 to 2,147,483,647 |
System.UInt32 | uint | 32 bits | 0 to 4,294,967,295 |
System.Int64 | long | 64 bits | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
System.UInt64 | ulong | 64 bits | 0 to 18,446,744,073,709,551,615 |
System.Single | float | 32 bits | ±1.5 × 10⁻⁴⁵ to ±3.4 × 10³⁸ |
System.Double | double | 64 bits | ±5.0 × 10⁻³²⁴ to ±1.7 × 10³⁰⁸ |
System.Decimal | decimal | 128 bits | ±1.0 × 10⁻²⁸ to ±7.9 × 10²⁸ |
System.Char | char | 16 bits | Unicode character |
Struct Example
Below is a simple struct
representing a 2‑D point:
public struct Point
{
public double X { get; }
public double Y { get; }
public Point(double x, double y)
{
X = x;
Y = y;
}
public double Length() => Math.Sqrt(X * X + Y * Y);
}
Try it in the playground