An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
@Adel , Welcome to Microsoft Q&A, based on your code, you want to return the size of unmanaged type if T is unmanaged type and return the default size if T is managed type.
First, I want to mention that we could not use lambda expression in the generic constraint.
We could create the method with constraint like the following:
static unsafe int SizeOf<T>() where T : unmanaged
{
return sizeof(T);
}
Second, I have found the method to replace the 'is T unmanaged', but it is still hard to achieve you wanted.
The following code can be used to check if T is unmanaged.
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;
}
}
However, When I use it in the method, it will give the complie error because we could not convert common T to unmanaged T.
Finally, I think we need to separate the two cases.
Like the above method:
static unsafe int GetSizeforunmanaged<T>() where T : unmanaged
{
return sizeof(T);
}
static unsafe int GetSizeformanaged<T>()
{
return IntPtr.Size;
}
//=> is T unmanaged ? SizeOf<T> : IntPtr.Size;
static void Main(string[] args)
{
int result=0;
result = GetSizeforunmanaged<int>();
Console.WriteLine(result);
result = GetSizeformanaged<string>();
Console.WriteLine(result);
}
We could use complie error to check if type is unmanaged.
Like the following:
If we used managed type in the GetSizeforunmanaged method, visual studio will give me a complie error.
Best Regards,
Jack
Hope my exmplanation could help you.
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.