Invoke an Overloaded Constructor through this keyword (What's the Different between this two Sample code?)
- by Alireza Dehqani
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
// Sample
Sample ob = new Sample(); // line1
// Output for line1
/*
* Sample(int i)
* Sample()
/
// Sample2
Sample2 ob2 = new Sample2(); // line2
// Output for line2
/
* Sample2()
*/
}
}
class Sample
{
// Fields
private int a;
// Constructors
public Sample(int i) // Main Constructor
{
Console.WriteLine(" Sample(int i)");
a = i;
}
// Default Constructor
public Sample()
: this(0)
{
Console.WriteLine(" Sample()");
}
}
class Sample2
{
// fields
private int a;
// Constructors
public Sample2(int i)
{
Console.WriteLine("Sample2(int i)");
a = i;
}
public Sample2()
{
Console.WriteLine("Sample2()");
a = 0;
}
}
}