Constructors in C #

I read a lot about why constructors are useful, and all the resources found indicate that constructors are used to initialize instances of your classes. A key advantage of using a constructor is that it ensures that the object goes through the correct initialization before use, often taking parameters. This helps ensure the integrity of the object and helps make applications written with object-oriented languages ​​more reliable.

By default, C # creates an empty default constructor if no constructors are specified in the class.

Most of the examples I find point to something like this:

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

Now, what is the practical point of creating a constructor, when you can specify properties,

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

And initialize it like this:

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

I cannot bow my head to having to explicitly create a constructor. I would appreciate if someone would give me a good practical example.

+5
source share
9 answers

Now, what is the practical point of creating a constructor when you can specify properties;

The advantage of having a constructor that is different from the standard one is that you are forced to pass all the necessary dependencies to it. This ensures that upon initialization the object will have everything that is required for proper operation.

+4
source

Although you can initialize the properties as shown in the figure:

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

without a constructor, you can also not initialize any of the properties

 Car myCar = new Car(); 

This can lead to the class working poorly / not working at all.

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

This is especially useful if you are considering the case when you are working in a project with several team members. If your team members want to use your class with the correct constructor, you can already hint to them what properties need to be initialized in the class so that they can use the class correctly.

+10
source

Now, what is the practical point of creating a constructor when you can specify properties

There are four problems with an approach that exposes properties:

  • You cannot guarantee consistency after initialization . For example, if you want to make sure that a non-zero speed requires a non-zero transmission, you can no longer control this check.
  • You can not ensure consistency when multiple attributes must be updated atomically. In parallel situations, when both speed and gear must be updated at the same time, protected by a lock, an approach with independently open attributes will not be reliable
  • You are forced to change your object . This is not always desirable, especially if your object is intended for simultaneous use.
  • You are forced to disclose methods that your users may not need. . Even in situations where your users expect a mutable object, it may be undesirable to set separate setters; with this approach you have no other choice.

I can’t wrap my head in the need for explicit constructor creation.

Here is a brief demonstration of what you can do when your setters are not exposed:

 class Car { private readonly object lockObject = new object(); private int speed; private int gear; public int Speed { lock (lockObject) { return speed; } } public int Gear { lock (lockObject) { return gear; } } public int Gear{ get; } public Car(int speed, int gear) { // You can validate two attributes together if (speed != 0 && gear == 0) { throw new ArgumentException("Non-zero speed in zero gear"); } this.speed = speed; this.gear= gear; } public void SpeedUp(int increase) { lock(lockObject) { var newSpeed = Math.Max(Speed + increase, 0); if (newSpeed > 200) { throw new InvalidOperationexception("Cannot speed up past 200"); } // Concurrent users would not see inconsistent speed setting Speed = newSpeed; Gear = Speed / 25; } } } 

The main advantages are the ability to simultaneously configure in parallel environments and the way to ensure consistency of the original object.

+2
source

The practical example of your example is that you do not need to do new Car(0, 0); to instantiate, and instead just do it for default initialization:

 public Car() { speed = 0; gear = 0; } Car myCar = new Car(); 
+1
source

A custom constructor forces your class client to provide parameters. Initialization by properties a) is not required by code b) can provide a class that is not yet ready for use. In addition, you can hide speed or transmission properties from others.

+1
source

Depending on what your class is doing, you might want to do some initialization. For example, a class can intercept a static event when it is initialized or output it for debugging. While coding also gives you a point, you can set a breakpoint to abort any attempt to instantiate a class.

+1
source

The problem is that your Car class users must somehow know that they need to set the initial speed and gear of the car.

The next rule of the rule is that the constructor must create an object that is 100% ready for use.

+1
source

The concept of designers is a pretty old school. It goes back to the days of C and C ++ when you yourself manage all your pointers. The constructor would set most of the variables without changing the length to make sure that you did not get a general security error or segmentation error when executing the code.

Modern coders avoid constructors that take parameters. This is due to the difficulties that they cause when conducting automatic unit tests. It is perfectly normal to use classes that have only default constructors (constructors with no arguments) and initialize them with property or method calls after the fact.

+1
source

I would say that this will lead to how you want to achieve the goal of the class you are building.

In OO Programming, to achieve encapsulation, you will only access members through getters / seters. Again, it depends on how much you want to go with implementing the principles of OO.

An example of when you need to pass variables to the constructor is that if you have some initialization code in the constructor that needed these values.

 private int speed { get; set; } private int gear { get; set; } private bool reduceSpeed { get; set; } public Car(int speedCurrent, int gearCurrent) { speed = speedCurrent; gear= startGear; if (speed > 30) reduceSpeed = true; // do further processing with this. ... } 
+1
source

Source: https://habr.com/ru/post/1247053/


All Articles