Επεξεργασία

Κοινή χρήση μέσω


Using Constructors (C# Programming Guide)

When a class or struct is instantiated, its constructor is called. Constructors have the same name as the class or struct, and they usually initialize the data members of the new object.

In the following example, a class named Taxi is defined by using a simple constructor. This class is then instantiated with the new operator. The Taxi constructor is invoked by the new operator immediately after memory is allocated for the new object.

public class Taxi
{
    public bool IsInitialized;

    public Taxi()
    {
        IsInitialized = true;
    }
}

class TestTaxi
{
    static void Main()
    {
        Taxi t = new Taxi();
        Console.WriteLine(t.IsInitialized);
    }
}

A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new. C# 12 introduces primary constructors. A primary constructor specifies parameters that must be provided to initialize a new object. For more information, see Instance Constructors.

Unless the class is static, classes without constructors are given a public parameterless constructor by the C# compiler in order to enable class instantiation. For more information, see Static Classes and Static Class Members.

You can prevent a class from being instantiated by making the constructor private, as follows:

class NLog
{
    // Private Constructor:
    private NLog() { }

    public static double e = Math.E;  //2.71828...
}

For more information, see Private Constructors.

Constructors for struct types resemble class constructors. When a struct type is instantiated with new, a constructor is invoked. When a struct is set to its default value, the runtime initializes all memory in the struct to 0. Prior to C# 10, structs can't contain an explicit parameterless constructor because one is provided automatically by the compiler. For more information, see the Struct initialization and default values section of the Structure types article.

The following code uses the parameterless constructor for Int32, so that you're assured that the integer is initialized:

int i = new int();
Console.WriteLine(i);

The following code, however, causes a compiler error because it doesn't use new, and because it tries to use an object that hasn't been initialized:

int i;
Console.WriteLine(i);

Alternatively, objects based on structs (including all built-in numeric types) can be initialized or assigned and then used as in the following example:

int a = 44;  // Initialize the value type...
int b;
b = 33;      // Or assign it before using it.
Console.WriteLine("{0}, {1}", a, b);

Both classes and structs can define constructors that take parameters, including primary constructors. Constructors that take parameters must be called through a new statement or a base statement. Classes and structs can also define multiple constructors, and neither is required to define a parameterless constructor. For example:

public class Employee
{
    public int Salary;

    public Employee() { }

    public Employee(int annualSalary)
    {
        Salary = annualSalary;
    }

    public Employee(int weeklySalary, int numberOfWeeks)
    {
        Salary = weeklySalary * numberOfWeeks;
    }
}

This class can be created by using either of the following statements:

Employee e1 = new Employee(30000);
Employee e2 = new Employee(500, 52);

A constructor can use the base keyword to call the constructor of a base class. For example:

public class Manager : Employee
{
    public Manager(int annualSalary)
        : base(annualSalary)
    {
        //Add further instructions here.
    }
}

In this example, the constructor for the base class is called before the block for the constructor is executed. The base keyword can be used with or without parameters. Any parameters to the constructor can be used as parameters to base, or as part of an expression. For more information, see base.

In a derived class, if a base-class constructor isn't called explicitly by using the base keyword, the parameterless constructor, if there's one, is called implicitly. The following constructor declarations are effectively the same:

public Manager(int initialData)
{
    //Add further instructions here.
}
public Manager(int initialData)
    : base()
{
    //Add further instructions here.
}

If a base class doesn't offer a parameterless constructor, the derived class must make an explicit call to a base constructor by using base.

A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression. For example, the second constructor in the previous example can be rewritten using this:

public Employee(int weeklySalary, int numberOfWeeks)
    : this(weeklySalary * numberOfWeeks)
{
}

The use of the this keyword in the previous example causes this constructor to be called:

public Employee(int annualSalary)
{
    Salary = annualSalary;
}

Constructors can be marked as public, private, protected, internal, protected internal or private protected. These access modifiers define how users of the class can construct the class. For more information, see Access Modifiers.

A constructor can be declared static by using the static keyword. Static constructors are called automatically, immediately before any static fields are accessed, and are used to initialize static class members. For more information, see Static Constructors.

C# Language Specification

For more information, see Instance constructors and Static constructors in the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also