I suggest you ...

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:
http://stackoverflow.com/questions/7551461/c-sharp-generic-constraint-where-is-not-class/7557040#7557040

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[100];
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.

353 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Ross NordbyRoss Nordby shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    5 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...
      • Anonymous commented  ·   ·  Flag as inappropriate

        I'd love to have this. This would help tremendously with C++ interrop and implementing many other low-level things.

      • Hongfaan LEIHongfaan LEI commented  ·   ·  Flag as inappropriate

        [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.

      • HarryHarry commented  ·   ·  Flag as inappropriate

        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.

      Feedback and Knowledge Base