C# generic constraints allowed specifying that a type parameter must be a struct, but this included both managed structs (containing references) and unmanaged structs (containing only primitive types). There was no way to restrict generic types to only unmanaged types.
C# 7.3 introduces the unmanaged constraint, which restricts a generic type parameter to unmanaged types only. This enables safe use of pointers, stack allocation, and interop scenarios with generic code.
Code
csharp
public unsafe void ProcessBuffer<T>(T* buffer, int length) where T : unmanaged
{
for (int i = 0; i < length; i++)
{
buffer[i] = default;
}
}
// Usage
unsafe
{
int* intBuffer = stackalloc int[10];
ProcessBuffer(intBuffer, 10); // Works with int
Point* points = stackalloc Point[5];
ProcessBuffer(points, 5); // Works with unmanaged structs
}csharp
// No way to write truly generic unmanaged code
public unsafe void ProcessIntBuffer(int* buffer, int length)
{
for (int i = 0; i < length; i++)
{
buffer[i] = default;
}
}
public unsafe void ProcessPointBuffer(Point* buffer, int length)
{
for (int i = 0; i < length; i++)
{
buffer[i] = default;
}
}
// Had to write separate methods for each typeNotes
- Unmanaged types include primitives, enums, pointers, and structs containing only unmanaged types
- A constructed generic type only satisfies this constraint from C# 8.0 onwards, so
Wrapper<int>is rejected in C# 7.3 - The
unmanagedconstraint impliesstructand cannot be combined with thestructornew()constraints - Unmanaged types cannot contain references, including
string, arrays, or reference type fields - This constraint enables high-performance generic code with direct memory manipulation
- Commonly used with
Span<T>,stackalloc, and interop scenarios - A
stackallocexpression became usable as a method argument and inside conditionals in C# 8.0 - See ref struct C# 7.2 for a related feature that also lets low-level code work without boxing or heap allocation.
- See the generics, variance & boxing guide for the constraint system this belongs to.