Information Technology Reference
In-Depth Information
Constructors with Parameters
Like other methods, constructors
Can have parameters. The syntax for the parameters is exactly the same as for other
methods.
Can be overloaded.
When creating an instance of a class with the
new
operator, you are telling it which con-
structor to use by supplying the class name, along with any actual parameters for the
constructor, as the operand to the
new
operator.
For example, in the following code,
Class1
has three constructors: one that takes no
parameters, one that takes an
int
, and another that takes a
string
.
Main
creates an instance
using each one.
class Class1
{
int MyNumber;
string MyName;
public Class1() { MyNumber=28; MyName="Nemo"; } // Constructor 0
public Class1(int Value){ MyNumber=Value; MyName="Nemo"; } // Constructor 1
public Class1(String Name) { MyName=Name; } // Constructor 2
public void SoundOff()
{Console.WriteLine("MyName {0}, MyNumber {1}", MyName, MyNumber); }
}
class Program
{
static void Main()
{
Class1 a = new Class1(), // Call constructor 0.
b = new Class1(7), // Call constructor 1.
c = new Class1("Bill"); // Call constructor 2.
a.SoundOff();
b.SoundOff();
c.SoundOff();
}
}
This code produces the following output:
MyName Nemo, MyNumber 28
MyName Nemo, MyNumber 7
MyName Bill, MyNumber 0