Using fixed on generic types

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

 



Answer this question

Using fixed on generic types

  • pharaonix

    Is a constraint sufficient for allowing pointers something worth looking at in the next version of C# Something like T : Atomic
  • uanmi

    Thanks, James. The T : struct constraint makes sense to me. In theory can any value-class type be addressable

    Brian


  • John12312

    Brian Kramer wrote:

    In theory can any value-class type be addressable

    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 : struct

    should solve the problem but that wasn't working for me.



  • RandomLick

    As James say, C# is strong typed language and you try to fool the compiler!

  • Using fixed on generic types