Click here to Skip to main content
12,621,430 members (30,043 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

35.4K views
10 bookmarked
Posted

How to call an overloaded constructors in C#

, 15 Sep 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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    
}

License

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

Share

About the Author

Reiss
Program Manager
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralReason for my vote of 5 It should be obvious, but as you men... Pin
Walt Fair, Jr.15-Sep-11 8:42
subeditorWalt Fair, Jr.15-Sep-11 8: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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.161128.1 | Last Updated 15 Sep 2011
Article Copyright 2011 by Reiss
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid