If you want to call one constructor from
another in a class itself, then use this()
If you want to call base class constructor
from derived class constructor, then use base().
If you are not calling any base class
constructor from derived class, then always base class default constructor will
called.
Sample Program:
static class
Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
DerivedClass
objDerivedClass = new DerivedClass();
//Output
: BaseClass - Default constructor
// DerivedClass - Default constructor
DerivedClass
objDerivedClass1 = new DerivedClass("PageId1234");
//Output
: BaseClass - Default constructor
// DerivedClass - Default constructor
// DerivedClass - Overloaded constructor calling
Default constructor using this()
DerivedClass
objDerivedClass2 = new DerivedClass(10800,
"Student");
//Output
: BaseClass - Overloaded constructor
// DerivedClass - Overloaded constructor
calling base class constructor
Console.ReadLine();
}
}
public partial
class BaseClass
{
int
tempCommandTimeout = 0;
/// <summary>
/// Default constructor
/// </summary>
public
BaseClass()
{
tempCommandTimeout = 300;
Console.WriteLine("BaseClass - Default constructor");
}
/// <summary>
/// Overloaded constructor to Set Command-timeout
/// </summary>
/// <param
name="iCommandTimeout"></param>
public
BaseClass(int iCommandTimeout)
{
tempCommandTimeout =
iCommandTimeout;
Console.WriteLine("BaseClass - Overloaded constructor");
}
}
public partial
class DerivedClass
: BaseClass
{
string
TableName = "";
string
PageID = "";
/// <summary>
/// Default constructor
/// </summary>
public
DerivedClass()
{
this.TableName
= "Employee";
Console.WriteLine("DerivedClass - Default constructor");
}
/// <summary>
/// Overloaded constructor calling Default constructor using
this()
/// </summary>
/// <param
name="ePageID"></param>
public
DerivedClass(string ePageID)
: this()
{
PageID = ePageID;
Console.WriteLine("DerivedClass - Overloaded constructor calling
Default constructor using this()");
}
/// <summary>
/// Overloaded constructor calling base class constructor to
Set Command-timeout
/// </summary>
/// <param
name="iCommandTimeout"></param>
public
DerivedClass(int iCommandTimeout, string strTableName)
: base(iCommandTimeout)
{
TableName = strTableName;
Console.WriteLine("DerivedClass - Overloaded constructor calling base
class constructor");
}
}