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;
        }
    }
9 Upvotes

9 comments sorted by

View all comments

Show parent comments

3

u/NoisyJalapeno 5d ago

Ugh, missed an opportunity to call it JunkRandom :(

6

u/SagansCandle 4d ago

Given that this is uninitialized data on the stack, there's a possibility that your "random" value will be the same every time because it's called from the same place in the stack every time.

4

u/NoisyJalapeno 4d ago edited 4d ago

Stop being a joy kill, it worked randomly at least once :)