+ 2

Constructor v/s creating an object.

If we are using new keyword for calling constructor then how it is different than creating an object.

21st Feb 2020, 4:49 PM
Abhishek Pandey
Abhishek Pandey - avatar
3 Réponses
+ 3
With the keyword new you are creating an object by calling the constructor.
21st Feb 2020, 5:00 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
A constructor is a defined method on a type which takes a specified number of parameters and is used to create and initialize an object. An object initializer is code that runs on an object after a constructor and can be used to succinctly set any number of fields on the object to specified values. The setting of these fields occurs after the constructor is called. You would use a constructor without the help of an object initializer if the constructor sufficiently set the initial state of the object. An object initializer however must be used in conjunction with a constructor. The syntax requires the explicit or implicit use (VB.Net and C#) of a constructor to create the initial object. You would use an object initializer when the constructor does not sufficiently initialize the object to your use and a few simple field and/or property sets would. https://stackoverflow.com/questions/740658/whats-the-difference-between-an-object-initializer-and-a-constructor
21st Feb 2020, 5:12 PM
Trần Tân An Nguyễn
Trần Tân An Nguyễn - avatar
+ 1
class_name() -> this makes a call to the constructor which is preceded by the 'new' keyword to create an object. new class_name() -> this complete line will create a new object by calling the constructor of the class.
21st Feb 2020, 5:13 PM
Avinesh
Avinesh - avatar