Instantiation of Variables

Source: Internet
Author: User

An object of a class is called an instance. Some variables must be instantiated by adding New when being defined, and some variables do not need New when being defined. For example, Dim EnCard asnew CardInfoEntity and Dim dt as Datatable. Why? In fact, adding New is to instantiate its variables and allocate space for them. without adding New, only variables are defined and no space is allocated for them. So when is the time for variable declaration and instantiation? Example:

<Span style = "font-size: 14px;"> namespace Recharge {class Class1 {Class2 class2 = new Class2 (); // This is instantiated when the member object is declared. Public Class1 () {// class2 = new Class2 (); // This declares only member objects when defining a class. When creating a class object instance, then, the object members in the class are instantiated in a unified manner. Class2.output () ;}}</span>

 

 
<Span style = "font-size: 14px;"> namespace Recharge {class Class2 {int B = 22; // This is instantiated (initialized) when the member variable is declared ). Public Class2 () {// B = 22; // This is declared only when the member variable is defined. When creating a class object instance, // initialize the members of the class through the class constructor. } Public void output () {Console. WriteLine (B. ToString () ;}}</span>

 

Declarations and instantiation (initialization) are different actions that are clearly defined. We recommend that you separate them. In the code automatically generated by Microsoft, A privatevoid InitializeComponent () function is called in the class constructor to instantiate (initialize) the class members ), in a class, only the Members are declared. Although the class can be instantiated in syntax when defining declared variables, this is obviously not a clear concept. All member instances of the class are created only when the class instance is created. It is recommended that this rule be reflected in the program writing.

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.