0

Constructor Overloading in C#

 1 year ago
source link: https://code-maze.com/constructor-overloading-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Constructor Overloading in C#

Publisher Logo

We value your privacy

We and our store and/or access information on a device, such as cookies and process personal data, such as unique identifiers and standard information sent by a device for personalised ads and content, ad and content measurement, and audience insights, as well as to develop and improve products. With your permission we and our partners may use precise geolocation data and identification through device scanning. You may click to consent to our and our partners’ processing as described above. Alternatively you may click to refuse to consent or access more detailed information and change your preferences before consenting. Please note that some processing of your personal data may not require your consent, but you have a right to object to such processing. Your preferences will apply to this website only. You can change your preferences at any time by returning to this site or visit our privacy policy.

Constructor Overloading in C#

Posted by Code Maze | Updated Date Oct 26, 2022 | 0

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

In this article, we are going to talk about constructor overloading in C#. We’ll look at the different ways to implement it in an application. 

While we look at constructor overloading in this article, we have an existing article on constructors that can act as a refresher before we start.

To download the source code for this article, you can visit our GitHub repository.

Let’s begin.

What is Constructor Overloading in C#?

Constructor Overloading is a technique to define multiple constructors within a class with different sets of parameters to achieve polymorphism.

We can overload constructors in C# just like methods. We can do so by changing the signatures by using a different number, or type of parameters.

Given that we have more than one type of parameter in the constructor, we can also change their order and achieve constructor overloading.

Let’s look at each type in detail.

To start, let’s create a class Animal:

public class Animal
public string Name { get; set; }
public string Type { get; set; }
public int Age { get; set; }
public string Speak()
return string.Format("Hi! My name is {0}, and I am a {1} years old {2}.", Name, Age, Type);
public class Animal
{
    public string Name { get; set; }
    public string Type { get; set; }
    public int Age { get; set; }

    public string Speak()
    {
        return string.Format("Hi! My name is {0}, and I am a {1} years old {2}.", Name, Age, Type);
    }
}

This is a simple class that contains three properties: Name, Type, Age, and a method Speak().

Different Numbers of Parameters

We can create multiple constructors with the same name i.e. overload them if the number of parameters in them is different:

public Animal()
Name = "Daffy";
Type = "duck";
Age = 85;
public Animal()
{
    Name = "Daffy";
    Type = "duck";
    Age = 85;
}

We have a default constructor for the Animal class that sets a default value for all the properties. However, we can make this assignment dynamic:

public Animal(string name, string type, int age)
Name = name;
Type = type;
Age = age;
public Animal(string name, string type, int age)
{
    Name = name;
    Type = type;
    Age = age;
}

The parameterized constructor takes three parameters that we assign to the properties Name, Type, and Age. In this way, even when they share the name, the compiler treats both of these constructors as different.

Now we can test both constructors using the Speak() method:

var animal = new Animal();
string expected = "Hi! My name is Daffy, and I am a 85 years old duck.";
string actual = animal.Speak();
Assert.Equal(expected, actual);
var animal = new Animal();

string expected = "Hi! My name is Daffy, and I am a 85 years old duck.";
string actual = animal.Speak();

Assert.Equal(expected, actual);

As expected, the constructor without any parameters sets default values to the class properties.

Now, when executing the parameterized constructor, we get the values that we pass while instantiating:

var animal = new Animal("Bugs", "bunny", 84);
string expected = "Hi! My name is Bugs, and I am a 84 years old bunny.";
string actual = animal.Speak();
Assert.Equal(expected, actual);
var animal = new Animal("Bugs", "bunny", 84);

string expected = "Hi! My name is Bugs, and I am a 84 years old bunny.";
string actual = animal.Speak();

Assert.Equal(expected, actual);

Different Types of Parameters

We can also overload a constructor having the same number of parameters if at least one of the parameters is a different type:

public Animal(string name, string type, int age)
Name = name;
Type = type;
Age = age;
public Animal(string name, string type, int age)
{
    Name = name;
    Type = type;
    Age = age;
}

Here, we have a constructor that takes 2 parameters of type System.String and another of type System.Int32. We can overload this constructor by changing the type of any parameter:

public Animal(string name, string type, string age)
Name = name;
Type = type;
Age = Convert.ToInt32(age);
public Animal(string name, string type, string age)
{
    Name = name;
    Type = type;
    Age = Convert.ToInt32(age);
}

The constructor in the second example takes the same number of parameters. However, the parameter to enter age is of type System.Int32 in the former constructor while it’s System.String in the latter.

Let’s test the new constructor using the Speak() method:

var animal = new Animal("Sylvester", "cat", "83");
string expected = "Hi! My name is Sylvester, and I am a 83 years old cat.";
string actual = animal.Speak();
Assert.Equal(expected, actual);
var animal = new Animal("Sylvester", "cat", "83");

string expected = "Hi! My name is Sylvester, and I am a 83 years old cat.";
string actual = animal.Speak();

Assert.Equal(expected, actual);

Different Order of Parameters

Another way to overload constructors is by changing the order of parameters in the constructors:

public Animal(string name, string type, int age)
Name = name;
Type = type;
Age = age;
public Animal(string name, string type, int age)
{
    Name = name;
    Type = type;
    Age = age;
}

We have a constructor from our previous example. We can overload it by keeping the same number and type of parameters while reordering them:

public Animal(string type, int age, string name)
Name = name;
Type = type;
Age = age;
public Animal(string type, int age, string name)
{
    Name = name;
    Type = type;
    Age = age;
}

In the example above, both constructors have the same number of parameters as well as the same type of parameters i.e. 2 System.String types and 1 System.Int32 type.

However, the order of these parameters is different and hence the compiler acknowledges the latter constructor as a new one:

var animal = new Animal("mouse", 69, "Speedy");
string expected = "Hi! My name is Speedy, and I am a 69 years old mouse.";
string actual = animal.Speak();
Assert.Equal(expected, actual);
var animal = new Animal("mouse", 69, "Speedy");

string expected = "Hi! My name is Speedy, and I am a 69 years old mouse.";
string actual = animal.Speak();

Assert.Equal(expected, actual);

With this type of constructor overloading, however, we need to be aware of a caveat:

public class Animal
public Animal(string name, string type) { }
public Animal(string type, string name) { }
public class Animal
{
    public Animal(string name, string type) { }

    public Animal(string type, string name) { }
}

This is not a valid example of  constructor overloading where we changed the orders of name and type parameters.

This results in a compiler error “Type ‘Animal’ already defines a member called ‘Animal’ with the same parameter types” on the second constructor.

The reason behind the error is that the compiler only cares about the types and orders of parameters. There is a constructor that takes 2 System.String arguments already. Hence, there is an error on the second declaration.

However, there is one improvement that we can make to these examples discussed here. While implementing constructor overloading, we introduced some duplicate code. This problem can be easily addressed by constructor chaining.

Conclusion

In this article, we learned about constructor overloading in C#.  We looked at how we can have multiple constructors with varying signatures according to the name, type, or order of parameters within the same class. 

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

Share:

Subscribe
guest
Label
0 Comments
booklet-200px-width-min.png

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices.

Leave this field empty if you're human:

© Copyright code-maze.com 2016 - 2022

wpDiscuz


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK