dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.16k stars 4.71k forks source link

S.R.CS.Unsafe: Add unsafe operations for ref returns and locals #17968

Closed jkotas closed 4 years ago

jkotas commented 8 years ago

Roslyn is adding support for ref returns and locals (https://github.com/dotnet/roslyn/issues/118). S.R.CS.Unsafe should provide operations that allow taking advantage of ref returns and locals in unsafe code.

public static class Unsafe
{
    // Reinterprets the given reference as a reference to a value of type TTo
    public static ref TTo As<TFrom,TTo>(ref TFrom source);

    // Add element offset to the given reference.
    public static ref T Add<T>(ref T source, int elementOffset);

    // Subtract element offset to the given reference.
    public static ref T Subtract<T>(ref T source, int elementOffset);

    // Determines whether the specified references point to the same location.
    public static bool AreSame<T>(ref T a, ref T b);
}

Edit: Updated with the revised proposal

jkotas commented 8 years ago

The null refs cannot be manufactured in C# directly, but they are possible to manufacture by unsafe code. They can be checked for null using Unsafe.AsPointer(ref valueRef) == null.

VSadov commented 8 years ago

@omariom refs existed in C# since v1.0 in a form of ref parameters. So far there was not a lot of need to null-check them. :-)

It is possible to manufacture a "null" ref, but language ignores such possibility as conceptually impossible, - just like regular locals somehow not having actual storage behind them. Behavior in such cases is not specified and at best would lead to NREs.

In practice the only cases of "null" refs that I have ever seen were results of bugs in the compiler or JIT.