C
C#15mo ago
Figure

✅ Constructors

If Constructors are just a method called when a class is created, how does the new operator in combination with the constructor make a class, id constructors are just a method that sets initial values.
11 Replies
mtreit
mtreit15mo ago
Constructors - C# programming guide - C#
A constructor in C# is called when a class or struct is created. Use constructors to set defaults, limit instantiation, and write flexible, easy-to-read code.
mtreit
mtreit15mo ago
Constructors are special. They're not exactly like any other method.
Figure
FigureOP15mo ago
I get that it doesnt have a return type and have the same name of name of its class but how does calling it with the new operator also make the class.
mtreit
mtreit15mo ago
That's handled by the runtime
Figure
FigureOP15mo ago
ok thank you
mtreit
mtreit15mo ago
If you look at what the C# code compiles down to (on a site like https://sharplab.io) you can see that new actually compiles to the newobj MSIL instruction, and that eventually means the runtime does certain things like allocating the actual memory for the instance, initializes fields, calls the constructor that the class defines, etc.
Figure
FigureOP15mo ago
ok il look into that thank you
mtreit
mtreit15mo ago
OpCodes.Newobj Field (System.Reflection.Emit)
Creates a new object or a new instance of a value type, pushing an object reference (type O) onto the evaluation stack.
sibber
sibber15mo ago
(you don't need to worry/know about any of that tho)
Figure
FigureOP15mo ago
ok
sibber
sibber15mo ago
/close if you have no further questions :)
Want results from more Discord servers?
Add your server