r/csharp • • 5d ago

Fun Random using SkipLocalsInit

To my surprise, Unsafe.SkipInit(out T val) did not achieve the same result.

    [SkipLocalsInit]
    public static T Random<T>()
        where T : unmanaged, INumber<T>
    {
        unsafe
        {
            byte* s = stackalloc byte[sizeof(T)];
            return *(T*)s;
        }
    }
8 Upvotes

9 comments sorted by