✅ Newbie question on Random function
When making a random function what is the significance of the first line. I can't understand what it means here:
Random rnd = new Random(); <-----
int num = rnd.Next();
I know the second line generates a random integer using ".Next" but "Random" doesn't make sense to me
14 Replies
Are you familiar with Object Oriented Programming? This line essentially creates an object for you which has the capabilities to generate "random" numbers
The object is of the class
Random
. This object will be assigned to a variable that is called rnd
in this caseOh, is this similar to how String is used?
You can certainly write
string s = new string(...);
(Although you'd rather do string s = "something";
)aha
okay I think I can wrap my head around that lol. Thank you ^^
btw are you working on .NET Framework or .NET 5 and later?
.NET 7
Then you should use
Random rnd = Random.Shared;
that's a shared instance, that is set up properlyI didn't really understand what they meant so I just chose that
That's perfectly fine since this is the latest release version
may I ask what .shared does
Ah, I added it to my message.
that's a shared instance, that is set up properly.I forgot to mention that this is also thread-safe "Set up properly" as in "seed is already set for that object"
by seed do you mean a seed that's used to generate random numbers?
Correct
Without seed, you'd get the same numbers in the same order everytime
ohh okay
I guess I should try to take some newer tutorials for the formatting lol
thanks