C
C#2y ago
PunMister

✅ 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
HimmDawg
HimmDawg2y ago
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 case
PunMister
PunMisterOP2y ago
Oh, is this similar to how String is used?
HimmDawg
HimmDawg2y ago
You can certainly write string s = new string(...); (Although you'd rather do string s = "something";)
PunMister
PunMisterOP2y ago
aha okay I think I can wrap my head around that lol. Thank you ^^
HimmDawg
HimmDawg2y ago
btw are you working on .NET Framework or .NET 5 and later?
PunMister
PunMisterOP2y ago
.NET 7
HimmDawg
HimmDawg2y ago
Then you should use Random rnd = Random.Shared; that's a shared instance, that is set up properly
PunMister
PunMisterOP2y ago
I didn't really understand what they meant so I just chose that
HimmDawg
HimmDawg2y ago
That's perfectly fine since this is the latest release version
PunMister
PunMisterOP2y ago
may I ask what .shared does
HimmDawg
HimmDawg2y ago
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"
PunMister
PunMisterOP2y ago
by seed do you mean a seed that's used to generate random numbers?
HimmDawg
HimmDawg2y ago
Correct Without seed, you'd get the same numbers in the same order everytime
PunMister
PunMisterOP2y ago
ohh okay I guess I should try to take some newer tutorials for the formatting lol thanks
Want results from more Discord servers?
Add your server