Unmanaged generic type constraint + generic pointers
Add an "unmanaged"/"blittable" generic type constraint and use it to allow generic pointers and related features. Related post by Eric Lippert:
The end result would allow this sort of code:
unsafe void DoSomeStuff<T>() where T : unmanaged
T t = new T();
T* tPointer = &t;
T* aBunchOfT = stackalloc T;
var tSize = sizeof(T);
byte* aBunchOfBytes = stackalloc byte[tSize * 100];
T* aBunchOfCastedT = (T*)bunchOfBytes;
Performance critical generic data structures, particularly those using preallocated pools of memory, would be a good example use case for this.
Currently, a data structure using pointers to represent data would either need to be type specialized or its users would end up casting pointers. Type specialization hurts code reusability. Requiring external pointer casts is error prone and infects other code with unsafe code requirements. Generic pointers make it easy to modularize the reusable unsafe bits, allowing relatively-low-maintenance drop-in replacements for platforms that don't allow unsafe code.
Adding support for an unmanaged constraint and generic pointers would make reusable unsafe code cleaner and more reliable.
I'd love to have this. This would help tremendously with C++ interrop and implementing many other low-level things.
Frank Niemeyer commented
F# already has this feature. Shameless plug: You can use my library if you want to do such things from C# today (albeit the "unmanaged" trait is not tracked by C#, obviously, so be careful): https://bitbucket.org/frank_niemeyer/nativeinterop :D
Really good stuff
Hongfaan LEI commented
[System.Security.SecuritySafeCritical] versions of UnmanagedMemoryAccessor/SafeBuffer .Read/Write/ReadArray/WriteArray<T> can be done very easily (by .Net/CLR team) if C# has this feature.
We would absolutely love to have this! Additionally, I think this would help the SIMD project and RyuJIT so the generic Vector<T> type can be constructed from a generic pointer T* also and not only from e.g. an IntPtr. So type safety would still apply.