Search code examples
c#generics

Difference between unmanaged and struct constraints in c# generics


where T : struct -Here T must be a value type.

where T : Unmanaged -Here T must not be a reference type.

What is the difference between struct and unmanaged if both are used for value types?


Solution

  • According to https://blog.jetbrains.com/dotnet/2018/07/19/unmanaged-delegate-enum-type-constraints-c-7-3-rider-resharper/

    In order to satisfy the unmanaged constraint, a type must be a struct and all the fields of the type must fall into one of the following categories:

    • Have the type sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, IntPtr or UIntPtr.
    • Be an enum type.
    • Be a pointer type.
    • Be a user-defined struct that satisfies the unmanaged constraint.

    So the unmanaged constraint is more constraining than the struct constraint.