C
C#9mo 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
mtreit9mo 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
mtreit9mo ago
Constructors are special. They're not exactly like any other method.
Figure
Figure9mo 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
mtreit9mo ago
That's handled by the runtime
Figure
Figure9mo ago
ok thank you
mtreit
mtreit9mo 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
Figure9mo ago
ok il look into that thank you
mtreit
mtreit9mo 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
sibber9mo ago
(you don't need to worry/know about any of that tho)
Figure
Figure9mo ago
ok
sibber
sibber9mo ago
/close if you have no further questions :)