The C# compiler complains on the following code, yet the non-generic version works.
The error is:
Error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
static unsafe void generic_version<T>(T[] arr)
{
fixed (T* pt = arr) // error
{
}
}
// non-generic version
static unsafe void int_version(int[] arr)
{
fixed (int* pt = arr) // this works
{
}
}
Any ideas why this is the case
Thanks,
Brian

Using fixed on generic types
pharaonix
uanmi
Thanks, James. The T : struct constraint makes sense to me. In theory can any value-class type be addressable
Brian
John12312
No, the struct constraint is too weak. You can only declare pointers to a very restricted set of structs (they can't contain any reference type members).
AyendeRahien
That was one of the first things I suggested back during the Whidbey beta period. Unfortunately I don't think it's high up on their priority list, since there only seems to be a handful or so of us actually using unsafe code.
glasssd
Well, as the error says you cannot declare a pointer to a managed type. T can be any type, managed or unmanaged. In theory,
static
unsafe void generic_version<T>(T[] arr) where T : structshould solve the problem but that wasn't working for me.
RandomLick