Click here to Skip to main content
15,124,487 members
Articles / Programming Languages / C#
Alternative
Tip/Trick
Posted 20 Sep 2011

Tagged as

Stats

10.4K views
1 bookmarked

How to call an overloaded constructors in C#

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
20 Sep 2011CPOL
All three of the Something methods could be replaced with a single definition of the form:public Something(string name = "default", index = -1){ myName = name; myIndex= index; DoStuff();}

All three of the Something methods could be replaced with a single definition of the form:


C#
public Something(string name = "default", index = -1)
{
    myName = name;
    myIndex= index;

    DoStuff();
}

License

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

Share

About the Author

Robert Ludwig
United States United States
No Biography provided

Comments and Discussions

 
GeneralAlso should be good to note, this was introduced in .NET 4 a... Pin
Tony D Great27-Sep-11 3:46
MemberTony D Great27-Sep-11 3:46 
GeneralIf you do this, you can no longer use Activator.CreateInstan... Pin
Richard Deeming22-Sep-11 8:02
mveRichard Deeming22-Sep-11 8:02 
GeneralHi Robert, in this scenario you are correct, but sometimes y... Pin
Reiss20-Sep-11 22:02
professionalReiss20-Sep-11 22:02 
Hi Robert, in this scenario you are correct, but sometimes you may still need overloaded constructors and so using defaults like you have may not always work, or you have to duplicate the default value in multiple places which introduces human error if you have to change the default value.

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.