Constructors - are they really necessary?

mp3909

Well-known member
Joined
Apr 22, 2018
Messages
61
Location
UK
Programming Experience
3-5
Hi,

So I just learnt a new concept in C#.
That is, the set and get methods which allow us to set the value of private fields in our classes and to also retrieve their values.
An example code is shown below.
Since we can set the values using the set method as shown in the code below (i.e. setting the private field _id), I am now starting to wonder, do we actually need constructors at all since the set method serves the same purpose?

C#:
using System;
namespace ConsoleApp33
{
    class Student
    {
        private int _id;
    
        public int Id
        {
            set
            {
                if(value <= 0)
                {
                    throw new Exception("Id cannot be negative");
                }
                this._id = value;
            }
            get
            {
                return this._id;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            s.Id = 101;
            Console.WriteLine(s.Id);
        }
    }
}
 
Constructors are used when creating the object, properties are used after creation of the object, properties can also be set again multiple times.
Constructors may be used to set the initial values, or require input for those when object is created.

There are also object initializers that can be used as shorthand object creation to set properties when creating the object without need to define constructors. How to: Initialize Objects by Using an Object Initializer (C# Programming Guide) | Microsoft Docs
 
What you're talking about are properties. The point of properties is that they behave like fields from the outside, i.e. the caller can just assign a value or get a value in the same way they would with a field, but they behave like methods from the inside, i.e. you can add as much code as you want besides actually setting a field, e.g. perform validation or raise an event. You should pretty much ALWAYS use properties in preference to public fields.

As far as constructors go, they are absolutely essential. Even if you don't write a constructor yourself, the system generates one for you when it compiles the class code. Every time you use the 'new' keyword to create an instance of a class, you're invoking a constructor of that class.

As far as writing your own constructors is concerned. That is less important these days, now that we have the object initialiser syntax that JohnH mentioned. Initialiser syntax doesn't really allow you to do anything new. It just allows you to do what you always could in a more succinct manner, e.g. where you would previously have done this:
var obj = new SomeType();

obj.Property1 = value1;
obj.Property2 = value2;
obj.Property3 = value3;

you can now do this:
var obj = new SomeType
          {
              Property1 = value1,
              Property2 = value2,
              Property3 = value3
          };

Setting properties on a newly created object in either way is more flexible than a constructor because the caller gets to choose which ones they set and which they don't. That also explains why you still need constructors sometimes though. One of the most common reasons to write your own constructor is that certain data is required in order to cerate the object in the first place. You can rely on the caller to provide required data after the fact so you shouldn't let them create an object without providing it. A constructor facilitates that.
 

Latest posts

Back
Top Bottom