C # Learning-Application of base and this in Constructor

Source: Internet
Author: User

Constructors can useBaseKeyword to call the constructor of the base class. For example:

 
Public ClassMANAGER: Employee
{
PublicManager (IntAnnualsalary)
:Base(Annualsalary)
{
//Add further instructions here.
}
}
 
 

In this example, the base class constructor is called before the constructor block is executed.BaseThe keyword can be used with or without parameters. Any parameters of the constructor can be usedBaseOr as part of the expression. For more information, seeBase (C # reference).

In a derived class, if you do not useBaseIf a base class constructor is explicitly called by a keyword, the default constructor is called implicitly (if any ). This means that the following constructor Declaration has the same effect:

PublicManager (IntInitialdata)
{
//Add further instructions here.
}


PublicManager (IntInitialdata)
:Base()
{
//Add further instructions here.
}
 



If the base class does not provide the default constructor, the derived class must useBaseExplicitly call the base constructor.

You can use the this keyword to call another constructor in the same object. AndBaseSame,ThisCan be used with or without parameters. Any parameters in the constructor can be usedThisOr as part of the expression. For example, you can useThisOverride the second constructor in the previous example:

 
PublicEmployee (IntWeeklysalary,IntNumberofweeks)
:This(Weeklysalary * numberofweeks)
{
}

In the previous exampleThisThis constructor is called because of the Keyword:

 
PublicEmployee (IntAnnualsalary)
{
Salary = annualsalary;
}
 
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.