Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a type fits the unmanaged constraint in C#?

How do I check if a type T fits the unmanaged type constraint, such that it could be used in a context like this: class Foo<T> where T : unmanaged? My first idea was typeof(T).IsUnmanaged or something similar, but that isn't a property/field of the Type class

like image 494
John Avatar asked Dec 29 '18 11:12

John


People also ask

What is the keyword which is used to apply constraints on type parameter?

Object, you'll apply constraints to the type parameter. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class.

Can generic classes be constrained?

You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.


1 Answers

According to unmanaged constraint documentations:

An unmanaged type is a type that is not a reference type and doesn't contain reference type fields at any level of nesting.

Also it's mentioned in C# language design documentations about unmanaged type constraint:

In order to satisfy this 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 any enum type.
  • Be a pointer type.
  • Be a user defined struct that satisfies the unmanaged constraint.

Considerations

Usually calling MakeGenericType is the most reliable solution for validating generic type constraints which are enforced by CRL. Usually trying to implement validation by yourself is not a good idea because there may be a lot of rules which you should consider and there is always a chance for missing some of them. But be informed, at least at time of writing this answer, it's not working well for unmanaged constraint.

.NET Core have a RuntimeHelpers.IsReferenceOrContainsReferences but at the time of writing this answer, .NET Framework doesn't have such function. I should mention that even using IsReferenceOrContainsReferences is not completely reliable for this task.

For example see the issue which I posted here about two structure which doesn't have any reference type but one of them evaluated as managed, one of them unmanaged (maybe a compiler bug).

Anyway, for now depending to your preference and requirements, use one of the following solutions to detect which type can satisfy unmanaged generic type constraint.

Option 1 - Using MakeGenericType

As an option, to check if the type can satisfy the unmanaged constraint, you can use the following IsUnmanaged extension method'.

C# 7.3: It is supposed to be more reliable, but I should say, it's not. It seems for unmanaged constraint, CLR is not respecting the constraint and it's just a C# compiler feature. So at least for now, I recommend using the second option.

C# 8.0: Works as expected in C# 8.0

using System;
using System.Reflection;
public static class UnmanagedTypeExtensions
{
    class U<T> where T : unmanaged { }
    public static bool IsUnManaged(this Type t)
    {
        try { typeof(U<>).MakeGenericType(t); return true; }
        catch (Exception){ return false; }
    }
}

Option 2 - Writing your own method checking the documented rules

As another option, you can write your method checking documented rules for unmanaged constraint. The following code has more rules rather than other answer to be able to handle cases like int? or (int,int):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class UnmanagedTypeExtensions
{
    private static Dictionary<Type, bool> cachedTypes =
    new Dictionary<Type, bool>();
    public static bool IsUnManaged(this Type t)
    {
        var result = false;
        if (cachedTypes.ContainsKey(t))
            return cachedTypes[t];
        else if (t.IsPrimitive || t.IsPointer || t.IsEnum)
            result = true;
        else if (t.IsGenericType || !t.IsValueType)
            result = false;
        else
            result = t.GetFields(BindingFlags.Public | 
               BindingFlags.NonPublic | BindingFlags.Instance)
                .All(x => x.FieldType.IsUnManaged());
        cachedTypes.Add(t, result);
        return result;
    }
}

More Information

You may find the following links useful:

  • Docs - Unmanaged constraint
  • GitHub - C# 7.3 language design documents - Unmanaged type constraint
  • A blog post by Sergey Teplyakov about Dissecting new generic constraints in C# 7.3
  • A blog post by Maarten Balliauw about Unmanaged, delegate and enum type constraints
  • GitHub Issue - Please clarify the implementation details of unmanaged generic constraints
  • GitHub - Proposal: Unmanaged constructed types #1504
like image 129
Reza Aghaei Avatar answered Sep 24 '22 20:09

Reza Aghaei