Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors in C#

Tags:

c#

constructor

I've been reading a lot about why constructors are useful and all the resources I found specify that constructors are used to initialize the instances of your classes. A key benefit of using a constructor is that it guarantees that the object will go through proper initialization before being used, often accepting parameters. It helps ensure the integrity of the object and helps make applications written with object-oriented languages much more reliable.

By default in C# a default empty constructor is instantiated if no constructors are specified in a class.

Most examples I'm finding specify something like this;

public Car(int speedCurrent, int gearCurrent) {
    speed = speedCurrent;
    gear= startGear;
}

Car myCar = new Car(0, 0);

Now what's the practical point of creating the constructor when you can specify the properties;

public int speed { get; set; }
public int gear { get; set; }

And initialise it like this;

Car myCar = new Car();
myCar.speed = 0;
myCar.gear = 0;

I cannot wrap my head around the need of having the explicitly creating a constructor. I would appreciate if someone would give me a good practical example.

like image 342
tech-dev Avatar asked Apr 13 '16 14:04

tech-dev


People also ask

What is constructor function in C?

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

What is constructor and different types of constructors?

There are two types of constructors in Java: no-arg constructor, and parameterized constructor. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class.


1 Answers

Although you can initialize the properties like what you show:

Car myCar = new Car();
myCar.speed = 0;
myCar.gear = 0;

without constructor, you may also choose not to initialize any of the properties

Car myCar = new Car();

Which may cause the class to work poorly/not working at all.

The purpose of the constructor is to force you to initialize all the required properties (by design) before you are allowed to use the class instance.

This is especially useful if you consider a case where you work in a project with multiple team members. If your team members want to use your class, by having right constructor, you can already hint to them what properties needed to be initialized in the class in order for them to use the class properly.

like image 195
Ian Avatar answered Oct 04 '22 11:10

Ian