How do you get the current seed of Random in C#?

Indeed, the Seed isn't stored as it is not relevant for the algorithm after initialization. One of its derivatives, mj, is stored in the SeedArray though, you can check that using Reflection to compare both Random instances:

int subtraction = (Seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(Seed);
mj = MSEED - subtraction;
SeedArray[55]=mj;

So all you have to do is to check the last element (index 55) in the SeedArray. This is the only place Seed is used.

[Moved answer from deleted question How to determine if two Random instances have the same seed?]


Not sure on getting the seed, but you could save the value you give to the Random object. Remember, there are two constructors. The second is Random(Int32), so if you set the seed yourself (an easy enough value is Environment.TickCount), you could store that value somewhere before you pass it to the constructor. If you haven't read it yet, check out the MSDN documentation at https://docs.microsoft.com/en-us/dotnet/api/system.random.


This is not possible.

Instead, you can serialize the Random instance using binary serialization.
Random is [Serializable], and the seed and internal state will persist.

Note, however, that saving the random seed allows your players to predict the future, which is very useful if you allow saving in battle.

Also note that users can still save, open the chest, load, perform an action that generates a random number, then get a different item from the chest.

Tags:

C#

Random