{
//Private fields of class
int A, B;
//default Constructor
public Test1()
{
A = 10;
B = 20;
}
//Paremetrized Constructor
public Test1(int X, int Y)
{
A = X;
B = Y;
}
//Method to print
public void Print()
{
Console.WriteLine("A = {0}\tB = {1}", A, B);
}
static void Main()
{
Test1 T1 = new Test1(); //Default Constructor is called
Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called
T1.Print();
T2.Print();
Console.Read();
}}
one more example:
class Test3
{
public Test3()
{
Console.WriteLine("Instance Const");
}
static Test3()
{
Console.WriteLine("Static Const");
}
static void Main()
{
//Static Constructor and instance constructor, both are invoked for first instance.
Test3 T1 = new Test3();
//Only instance constructor is invoked.
Test3 T2 = new Test3();
Test3 t3 = new Test3();
Console.Read();
}
}
Jignesh TrivediPosted Sep 17, 2013, 12:30 AM
your code is correct.
are you facing any problem to create constructor?
Satyapriya NayakPosted Sep 16, 2013, 9:17 AM
Pavan RamamurthyPosted Sep 16, 2013, 8:41 AM
Jeetendra GundPosted Sep 16, 2013, 8:26 AM
public class mySampleClass {
public mySampleClass()
{
// This is the no parameter constructor method.
// First Constructor
}
public mySampleClass(int Age)
{
// This is the constructor with one parameter.
// Second Constructor
}
public mySampleClass(int Age, string Name)
{
// This is the constructor with two parameters.
// Third Constructor }
// rest of the class members goes here. }
This way also
Prasenjit DeyPosted Sep 16, 2013, 8:20 AM
{
//Private fields of class
int A, B;
//default Constructor
public Test1(int x = 10, int y = 20)
{
A = x;
B = y;
}
You also can do this. If you use optional parameter, you don't have to overload the constructor (for default constructor in your example), your work will be done just declare one constructor only