Method with the same name as the included class, but this method does not return type:
Public class myclass
{
Public myclass ()
{
}
// Rest of Class Definition
}
If no constructor is provided, the compiler creates a default constructor in the background. It can only Initialize all member fields as standard default values (for example, the reference type is null reference, the numeric data type is 0, and the bool value is false)
If a constructor with parameters is provided, the compiler will not automatically provide default constructor. the compiler will automatically provide default constructor only when no constructor is defined.
1. Static Constructor
This constructor is executed only once, and the previous constructor is an instance constructor. It will be executed as long as the class object is created.
Class myclass
{
Static myclass ()
{
// Initialization code
}
// Rest of Class Definition
}
One reason for writing a static constructor is that the class has some static fields or attributes. You need to initialize these static fields and attributes from the external source before using the class for the first time.
- A static constructor cannot contain any parameters. A class can have only one static constructor.
- No access modifier for the static Constructor
- A static constructor can only be a static member of a category and cannot access instance members.
- Although the list of parameters is the same, a constructor without parameters can coexist with a static constructor in the class. Because the static constructor is executed when the class is loaded, and the instance constructor is executed when the instance is created.
Assume that a user sets backcolor to indicate the background color to be used in the application.
Namespace consoleapplication2
{
Classprogram
{
Public static readonly color backcolor;
Static Program ()
{
Datetime now = datetime. now;
If (now. dayofweek = dayofweek. Saturday | now. dayofweek = dayofweek. Sunday)
{
Backcolor = color. Green;
}
Else
{
Backcolor = color. Red;
}
}
Private Program ()
{}
This code shows how the color settings are stored in static variables, which are initialized in the static constructor. Declare this field as a read-only type, indicating that its value can only be set in the constructor.
2. Call constructors from other constructors
Namespace consoleapplication3
{
Classcar
{
Privatestring description;
Privateuint nwheels;
Public Car (string description, uint nwheels)
{
This. Description = description;
This. nwheels = nwheels;
}
// Constructor
Public Car (string description)
: This (description, 4)
{}
Staticvoid main (string [] ARGs)
{
}
}
}
C # The constructor initialization operator can also contain calls to the constructor of the direct base class (use the same syntax, but use the base keyword instead of this)