65.9K
CodeProject is changing. Read more.
Home

How to call an overloaded constructors in C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (9 votes)

Sep 15, 2011

CPOL
viewsIcon

55543

A guide on how to call overload constructors in C#

Disclaimer: I wasn't really sure whether to post this or not as it is very baisc and I would exepect every programmer to know this, but after inheriting some code and reviewing it I came across this (names changed, but logic is the same)
namespace Dummy
{
    public class Something
    {
        private string myName;
        private int myIndex;

        public Something()
        {
            myName = "default";
            myIndex = -1;

            DoStuff(); 
        }

        public Something(string name)
        {
            myName = name;
            myIndex= -1;

            DoStuff(); 
        }

        public Something(string name, index)
        {
            myName = name;
            myIndex= index;

            DoStuff(); 
        }

        private void DoStuff()
        {
            // logic
        }
                    
        // rest of class definition    
}
Whilst this isn't truly horrific, it is not best practice as it contains code duplication and can be replaced with:
namespace Dummy
{
    public class Something
    {
        private string myName;
        private int myIndex;

        public Something() : this("default"){}

        public Something(string name) : this(name, -1) {}

        public Something(string name, index)
        {
            myName = name;
            myIndex= index;

            DoStuff(); 
        }

        private void DoStuff()
        {
            // logic
        }
                    
        // rest of class definition    
}