Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to call an overloaded constructors in C#

0.00/5 (No votes)
15 Sep 2011 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here