Click here to Skip to main content
15,880,405 members
Articles / Programming Languages / C#
Tip/Trick

How to call an overloaded constructors in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (10 votes)
15 Sep 2011CPOL 53.2K   10   11
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)

C#
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:

C#
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    
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Program Manager
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 It should be obvious, but as you men... Pin
Dr.Walt Fair, PE15-Sep-11 7:42
professionalDr.Walt Fair, PE15-Sep-11 7:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.