❔ can someone explain the me the new operator
Especially the syntax behind this example:
Random rnd = new Random();
Can u compare the random before the = with int, string and the random after then says that a random number should be generated and new simply says that it should be regenerated every time the program is executed?
29 Replies
new
is used to instantiate objects
in order to use a Random
, you need to create an instance of itso can u explain what an instance is.
it's like having a blueprint of a bike versus actually having a bike
new Random()
takes the "blueprint" of the Random
class definition and creates an actual object that you can call methods and things on
you can make as many different Random
objects as you want, all with their own individual stateso u can compare the first random with string, int, ...
?
You can't compare apples to oranges
you mean like why you don't need
new
to assign those types of variables?it defines the variable
because they have literal representations and are generally treated as values instead of instances of objects
yes, variable definitions are all the same
[type] [identifier] = [value]
So I define the varialbe as random and then I create it with new
correct
ty
looks like i can?
what you're asking isn't very clear
he intepreted your question as asking if you can literally compare a
Random
and a string
or int
with each other (in which case the answer would be no)ok
just to be clear what i "creat" with new ist called instance like when i write int Num = 1 is 1 the instance
of num
no, value types work differently
Creating something with 'new' is an instance, yes.
1
, or "1"
are literals, not instanceswhats the differences
srry if i ask Stupid questions
instances are objects created from a class literals are direct representations of constant values
got it
The new Random() gives you an instance of the Random class. The random class has methods you can call
Other than that, they are comparable to I think
Why do you want to compare the Random?
to understand now i know what new does
but tanks for ur version
Are you trying to compare like: 1 and a random number?
yes
as value
Then you have to first generate a random number
Which is done by calling the .Next public method of the Random class.
already did
public class Program11
{
static void Main(string[] args)
{
Random rnd = new Random();
int secretNum = rnd.Next(1, 2);
int numGuessed = 0;
do
{
Console.WriteLine("Enter a number between 1 and 10:");
numGuessed = Convert.ToInt32(Console.ReadLine());
} while (secretNum != numGuessed);
Console.WriteLine("You guessed it! It was {0}", secretNum);
}
}
Ah okay, nice!
but ty
I thought that you thought that the new Random() was giving you a random number 😛
But it seems you've figured it out!
then u got me i thought next just gives an interval
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.