Eugen1344 Eugen1344 - 1 month ago 5
C# Question

How to get a pointer of list?

So i know that list holds array inside it, so i need to get a pointer of unknown type of it (void*). It is pretty easy to do with arrays:

int[] items;
fixed (void* pointer = items)
{

}


So i need to do same thing for List

List<int> items;
fixed (void* pointer = items)
{

}


This code doesn't seems to work. I don't want to copy a list to a new array, i want to access a pointer to it's internal array

Answer

It's not possible to get a pointer to a List<T> - you can only get pointers to arrays of primitive types. (In that case, you get a pointer to the first element by getting its address.)

Depending on how big your list is, you can call ToArray() on the list and then get a pointer to the first element but this could be fairly expensive for large arrays.

Comments