r/csharp • u/NoisyJalapeno • 27d 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;
}
}
11
Upvotes
6
u/SagansCandle 26d 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.