Mayfield Global Knowledge Center



How do I overload a class constructor in C#?

In order to overload your class constructor you must specify multiple constructors with unique signatures. You can accomplish this by specifying more than one constructor with the same name with different types of parameters or different number of parameters. The following code show how you might distinguish constructors (or any other method) by signature:void MyConstructor(int p1); void MyConstructor(int p1, int p2);    // different number void MyConstructor(int p1, string s1); // different types

Below is a simple program that provides a good example of overloading the constructor:using System; using System.Collections.Generic; using System.Text; namespace ConstructorExample {     class MethodOverloading     {         // private member variables         private int Number1 = 0;         private int Number2 = 0;         private int Number3 = 0;         private string String1 = "Default String1";         private string String2 = "Default String2";         private string String3 = "Default String3";         // public accessor methods         public void DisplayVariables()         {             System.Console.WriteLine("Num1: {0}, Num2: {1}, Num3: {2}, String1: {3}, String2: {4}, String3: {5}", Number1, Number2, Number3, String1, String2, String3);         }         // constructors         public MethodOverloading(int Number1, int Number2, int Number3, string String1, string String2, string String3)         {             this.Number1 = Number1;             this.Number2 = Number2;             this.Number3 = Number3;             this.String1 = String1;             this.String2 = String2;             this.String3 = String3;         }         public MethodOverloading(int Number1, string String1)         {             this.Number1 = Number1;             this.String1 = String1;         }     }     class Tester     {         public void Run()         {             MethodOverloading mo1 = new MethodOverloading(100, 200, 300, "Mayfield", "Global", "KB");             mo1.DisplayVariables();             MethodOverloading mo2 = new MethodOverloading(10, "MGKB");             mo2.DisplayVariables();         }         static void Main()         {             Tester t = new Tester();             t.Run();         }     } }
The output looks like this:Num1: 100, Num2: 200, Num3: 300, String1: Mayfield, String2: Global, String3: KB Num1: 10, Num2: 0, Num3: 0, String1: MGKB, String2: Default String2, String3: Default String3

Would you like to...


del.icio.us

Print this page Print this page

Email this page Email this page

Post a comment Post a comment

Subscribe me

Add to favoritesAdd to favorites

User Opinions (4 votes)

100% thumbs up 0% thumbs down

How would you rate this answer?

Helpful
Not helpful
Thank you for rating this answer.

Visitor Comments

  1. Comment #1 (Posted by John T.)
    Thank you for a great article!

Related Questions

Attachments