I tried to write a code to check if a type is managed:
using System;
struct A
{
public int a;
public string s;
}
struct B<T> where T : unmanaged
{ }
class Program
{
public static bool IsManaged<T>()
{
try
{
typeof(B<>).MakeGenericType(typeof(T));
}
catch (Exception)
{
return true;
}
return false;
}
static void Main()
{
if (IsManaged<A>())
Console.WriteLine("Managed");
else
Console.WriteLine("Unmanaged");
}
}
But the output is Unmanaged
while A
is not unmanaged by definition:
An unmanaged-type is any type that isn’t a reference-type or constructed type, and doesn’t contain reference-type or constructed type fields at any level of nesting.
Is the a way to fix the code or is there any other way to check if a type is managed?