Constructor overloading in C#

C# allows you to reuse existing constructors when defining new constructors. Suppose we have a Person class.

    public class Person
    {
        public Person()
        {
        }

        public Person(String name)
            : this(name, 0, 0)
        {
        }

        public Person(String name, int age)
            : this(name, age, 0)
        {
        }

        public Person(String name, int age, float salary)
        {
            this.Name = name;
            this.Age = age;
            this.Salary = salary;
        }

        public override string ToString()
        {
            return "Name: " + this.Name + "\n" +
                    "Age: " + this.Age + "\n" +
                    "Salary: " + this.Salary + "\n";
        }

        public String Name { get; set; }
        public int Age { get; set; }
        public float Salary { get; set; }

    }

As you can see, the fourth constructor has been reused for defining the second and third constructors.

This entry was posted in C# and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?