CLR via C # learning notes (4) method Constructor

Source: Internet
Author: User
Document directory
  • Instance constructor of reference type
  • Value Type instance Constructor
  • Type constructor

The book CLR via C # has been roughly read twice before, but has never been able to understand it in depth, and a lot of content has been forgotten. Now I want to read it again, and write the read part, because the write process is also a process of deep understanding. This series is a learning record and can be easily accessed by myself later. If it is helpful to everyone, I am very happy. I read books selectively, so the order may be different from the order in the book.

Constructor is a special method for initializing a type instance to a valid state. Constructor is commonly used in metadata. It can be seen through the Il code. When creating an instance of the type, it is generally divided into three steps:

  • Allocates memory for the data fields of the instance.
  • Create object pointers and synchronize index blocks.
  • Call the instance constructor to set the initial state of the object.
Instance constructor of reference type

Before creating an object of the reference type, the memory allocated to the object is cleared before calling the instance constructor of the type, that is to say, all fields not displayed in the constructor will be set to 0 or null. Unlike the general method, an instance constructor can never be inherited. The following keywords cannot be used for the instance Constructor (Virtual new override sealed abstract ). If no constructor is defined in a class, the C # compiler defines a default non-argument constructor. The access modifier of the default constructor of the abstract class is protected. The constructor can initialize fields. However, the C # language provides a simple method to assign values to initialize fields. As follows:

public class User {    private int _age = 25;    private string _name = "oec2003";}

It is really convenient as above, but if there are several initialized instance fields and multiple overloaded constructors exist at the same time, you should put the initialization of the Instance field in a common constructor. Other constructor uses this to display and call the constructor, which can reduce the size of code generation, let's look at the example below.

public abstract  class User{    private int _age=25;    private string _name="oec2003";    private string _email = "oec2003@gmail.com";    public User(Int32 age)    {        this._age = age;    }    public User(string name)    {        this._name = name;    }    public User(Int32 age, String name, String email)    {        this._age = age;        this._name = name;        this._email = email;    }}

The correct statement should be as follows:

public abstract  class User{    private int _age;    private string _name;    private string _email;    public User()    {         _age=25;        _name="oec2003";        _email = "oec2003@gmail.com";    }    public User(Int32 age):this()    {        this._age = age;    }    public User(string name):this()    {        this._name = name;    }    public User(Int32 age, String name, String email):this()    {        this._age = age;        this._name = name;        this._email = email;    }}
Value Type instance Constructor

The constructor of the value type is very different from that of the reference type. The value type cannot contain constructor without parameters, if you explicitly specify a constructor without parameters, a compilation error occurs. As shown in the following code, a compilation error occurs:

struct User{    public Int32 _age;    public String _name;    public User()    {        _age = 25;        _name = "oec2003";    }}

The value type cannot contain constructors without parameters or initialize fields in the value type. The following Code cannot be compiled.

public struct User{    public Int32 _age=25;    public String _name="oec2003";}

There can also be constructor in the value type. However, this constructor must contain parameters and initialize all fields. Constructors that contain parameters but do not initialize all fields cannot be compiled. See the following code:

Public struct user {public int32 _ age; Public String _ name; // only the _ age public user (int32 age) {_ age = age;} public user (int32 age, string name) {_ age = age; _ name = Name ;}}

It can be seen that if the value type shows that all fields must be initialized by the constructor. If there are multiple constructors, each constructor must also Initialize all fields; otherwise, it cannot be compiled. If the value type does not contain constructors, all fields are set to 0 or null during instantiation.

Type constructor

A Type constructor is also called a static constructor. Static constructors can be used to reference types and value types. Unlike the instance constructor, a static constructor always has only one type and cannot contain parameters. Only static fields can be initialized in the static constructor. The following code shows the static constructor in the value type (which is different from the strength constructor. The value type allows the display of static constructor defining no parameters) and the reference type.

// Value type public struct user {public static int32 _ age; public static string _ name; static user () {_ age = 25; _ name = "oec2003 ";}} // reference type public class user {public static int32 _ age; public static string _ name; static user () {_ age = 25; _ name = "oec2003 ";}}

To prevent Code Compiled by developers from calling static constructors, the C # compiler defines static constructors as private, you cannot add access modifiers to the static constructor explicitly. If you do so, a compilation error occurs.

As mentioned above, the value type cannot assign values to instance fields. Otherwise, compilation errors may occur. However, you can assign values to static fields during the definition. See the following code:

Public struct user {public static int32 _ age = 25; // The static field Public String _ name = "oec2003" can be initialized correctly; // The instance field cannot be initialized due to an error}

Static constructor should not call the static constructor of the base class, because the static field is not inherited into the subclass, so this is meaningless.

Series of related articles

CLR via C # learning notes (1) primitive type value type reference type

CLR via C # Study Notes (2) packing and unpacking

CLR via C # learning notes (3) constants and fields (cosnt readonly)

CLR via C # learning notes (4) method Constructor

CLR via C # learning notes (5) Performance of static Constructors

CLR via C # learning notes (6) method Parameter Correlation (out ref Params)

 
Related Article

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.