Using multiple Constructors in CSharp
As mentioned in the previous article, CSharp allows you to use multiple constructors. What is the benefit of this?
Sometimes it happens that you need an object of the same class, but you do not necessarily have the same number of attributes. Let us take our example person again. It may be that we do not want each person to provide all the information about themselves. Maybe the firstname and lastname are enough for us. Perhaps we still need the age. Depending on how we want to design our program, we can also do that.
Example of using multiple constructors in CSharp
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Panjutorials { class Person { // the attributes of a Person int age; string firstname, lastname, eyeColor; // Constructor with 4 arguments public Person(string myFirstName, string myLastName, int myAge, string myEyeColor) { firstname = myFirstName; lastname = myLastName; age = myAge; eyeColor = myEyeColor; } // Constructor with 3 arguments public Person(string myFirstName, string myLastName, int myAge) { firstname = myFirstName; lastname = myLastName; age = myAge; } // Constructor with 2 arguments public Person(string myFirstName, string myLastName) { firstname = myFirstName; lastname = myLastName; } // Example for an action public void introduceOneSelf() { if(age != 0 && eyeColor != null) { Console.WriteLine("My name is " + firstname + " " + lastname + " and I am " + age + " years old " + " and my eye color is " + eyeColor + "."); } if(eyeColor == null && age != 0) { Console.WriteLine("My name is " + firstname + " " + lastname + " and I am " + age + " years old ."); } if (eyeColor == null && age == 0) { Console.WriteLine("My name is " + firstname + " " + lastname + "."); } } } }
And the main class could look like this
class Program { static void Main(string[] args) { // declaring the two Objects of Person Person denis = new Person("Denis", "Panjuta", 28, "green"); Person michi = new Person("Michael", "Müller", 35); Person heidi = new Person("Heidi", "Schmidt"); // Calling the action of each of the two objects denis.introduceOneSelf(); michi.introduceOneSelf(); heidi.introduceOneSelf(); // output to console Console.Read(); } }
As output we get:
My name is Denis Panjuta and I am 28 years old and my eye color is green.
My name is Michael Müller and I am 35 years old.
My name is Heidi Schmidt.
So you see, we have many options as to how we want to create our classes and objects.