Declaration and initialization of variables in C #

Source: Internet
Author: User

int i;

string text;

for (i = 0; i <; i++)

{

Text = "line" +convert.tostring (i);

Console.WriteLine ("{0}", text);

}

Console.WriteLine ("Last text in loop: {0}", text);

This code compilation also fails, the variable text must be declared and initialized before use, and text is initialized in the loop, and the value assigned to text is lost after the loop exits.

int i;

String text= "";

for (i = 0; i <; i++)

{

Text = "line" +convert.tostring (i);

Console.WriteLine ("{0}", text);

}

Console.WriteLine ("Last text in loop: {0}", text);

Only one simple type is declared, and there is no change, and no memory is allocated to the variable. A variable occupies only one piece of memory after it is assigned. If this memory-hogging behavior occurs only in loops, the value is actually a local variable that is outside the scope of the loop. Assigning a value outside the loop ensures that the value is a local value of the body code and is still within the scope of the value inside the loop.

Declaration and initialization of variables in C #

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.