C#: Constructor overloading

This entry is part 32 of 71 in the series C#

Often, you’ll want to have more than one method with the same name.  This is called method overloading.

The most common example of this is to have more than one constructor with the same name.  This is commonly known as constructor overloading.  

It allows you to create the object with different types of parameters, or a different number of parameters.

Constructor Overloading
using System;

namespace Overloading
{
    public class Square
    {
        // private variables
        private int length;
        private int width;
        private string color;

        // public methods
        public void DisplaySquare()
        {
            Console.WriteLine("Length: {0}, Width: {1}, Color: {2}", length, width, color);
        }

        // constructor
        public Square(int theLength, int theWidth)
        {
            length = theLength;
            width = theWidth;

            color = "Purple";

        }

        public Square(int theLength, int theWidth, 
                   string theColor)
        {
            length = theLength;
            width = theWidth;
            color = theColor;
        }
    }

    public class Program
    {
        static void Main()
        {
            Square square1 = new Square(4, 8);
            square1.DisplaySquare();
            Square blueSquare = new Square(3, 5, "blue");
            blueSquare.DisplaySquare();
            Console.ReadLine();
        }
    }
}

For example, in the Square object above, we have 2 constructors.  The first with only the length and width and the second with the color added as one of the input parameters.

The 2 constructors with different inputs are as shown below:

public Square(int theLength, int theWidth)
public Square(int theLength, int theWidth, string theColor)

In this example, you can say that the square will have a default color of Purple unless you pass a color parameter into the constructor when constructing the square object.

 

Series Navigation<< C#: Get & set for auto-implemented properties
C#: Method overloading >>

Leave a comment

Leave a Reply