S
S
Sticky Rain2020-11-06 09:14:59
C++ / C#
Sticky Rain, 2020-11-06 09:14:59

Why the new operator in C#?

Or rather, what does he do?

Another example:

(a[ new Random().Next(0, a.Length)]);

(Google is not banned for me, I just would like a maximum of explanations on the fingers for a beginner)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2020-11-06
@stiicky

Newbie explanation with CLR deepening.
This syntax was invented to be used in C# to call the constructor .
The constructor after compilation is a method named ".ctor" - because of this, it cannot be simply declared or called by hand.
There is a F# language in which a constructor is called without new - your example would look like this on it:
a[Random().Next(0, a.Length)]
Constructors are needed to initialize object instances.
I would advise you to move Random to a new variable so that you don't have to re-create it every time you want to pull a random element from the array.

B
basrach, 2020-11-14
@basrach

The new operator creates an instance of a type.
In this case, the type (class) is Random. To create an object (that is, an instance) of this type, you need to apply the new operator to this type.
The call to the constructor and the initialization of the object's fields occurs after the instance has been created. C# allows you to specify a "function" - a constructor (a type may have several) when creating an instance of a type - to initialize the created object immediately after creation.
Why do you need an instance of a type at all? Again using your code example - you want to use the Next method to get the next random number. The algorithm for calculating a pseudo-random number always works using some initial value; when creating an instance of a type, this value is initialized and stored in this particular instance of the type.
Related links.
https://docs.microsoft.com/en-us/dotnet/csharp/lan...
https://docs.microsoft.com/en-us/dotnet/csharp/lan...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question