Constructor and object initializer

Source: Internet
Author: User

Constructor and object initializer

Constructor:Used to instantiate an object.

Generally, a default no-argument constructor exists in the class or struct. If we manually write a constructor with parameters in the class, the constructor without parameters will be overwritten, but the constructor will not be overwritten, even if we have written a construction method with parameters in the struct, the construction method without parameters can still be used.

[When using the singleton mode, we can write a private constructor to prevent the class from being instantiated again in other classes and enhance the robustness of the Code .]

Static constructor:Used to initialize static members.

A class can have only one static constructor without any access modifiers and no parameters.

The static constructor initializes the static members in the class before the program creates the first instance or references any static members.

Object initializer:In a class, we usually use constructor to assign values to fields, attributes, and other Members to complete object initialization. However, when there are many fields and attributes in a class, it is impossible to define the constructor for various situations. In this case, we can use the "Object initiator" to assign values to fields and attributes, object initialization is completed.

The syntax format is as follows:

1 public class Test 2 {3 private void Start () 4 {5 AA B = new AA () {a = 1, B = true}; 6 AA a = new AA () {B = true, c = "str"}; 7} 8} 9 public class AA10 {11 public int a; 12 public bool B; 13 14 private string _ c; 15 public string c16 {17 get {return _ c;} 18 set {_ c = value;} 19} 20}

 

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.