Why Do you have to Create an instance of a Class in some cases for methods and not others?
I was trying to program the usual Random Number Generator earlier today as a guessing game. I kept running into an issue because I tried Random.Next(1,10); and it was spitting out an error. I then found an example of the code and it was having me create the line Random rnd = new Random(); and then I could use rnd.Next(1,10). Why is it that I can't use Random.Next but in other situations I can do something like variable.Length(); I'm confused as to why it's making me create an instance of a Random object to use a method but not when using things like Length or Convert.ToInt32();
12 Replies
The key difference is whether the class or method is static or not. That in turn is mostly dependant on whether the respective component contains instance specific state
I guess I still feel very new to C# so it seems confusing to me but I'll keep plugging away. Thanks.
Random.Next means you're accessing the Next method in that Random class.
Same thing like:
You can see the complete list of methods in Random class here https://learn.microsoft.com/en-us/dotnet/api/system.random?view=net-8.0
Makes sense but why can you use methods without creating objects in certain cases like on an array or variable? Is it because the object is already an instance of that type?
you can do that to statics
eg:
Ok. Thank you
aight, goodluck
Exactly this. An array is an instance, and a variable points to an instance of some object.
thanks
And there is no static Random.Next because random instances contain their seed data, so their result can be recreated if necessary (like for tests and stuff)
Hin
REPL Result: Success
Result: ValueTuple<int, int>
Compile: 428.848ms | Execution: 32.385ms | React with ❌ to remove this embed.
So randoms created with same seed yield same results
But the general recommendation if you want it to really be random is to use
Random.Shared.Next()
(available in .net 6+ iirc)