C # foreach Useful method specifically explains

Source: Internet
Author: User

Web-based data, said that foreach can not change the iteration variables, only access to iterate variables. Self-understanding is not very deep, through a few code validation, found that the use of foreach is also a bit special

Verification Method:

1. The iteration variable is int

Int[] Argint = {12,12,12,12,12};
foreach (int item in Argint)
{
item = 100;
}

Result: Compile does not pass, hint item is iteration variable, cannot assign value to it;


2. The iteration variable is a struct

public struct MYSTRUCT
{
public string Name {get; set;}
}

mystruct[] array = new mystruct[] {new MyStruct {name = "1"}, new MyStruct {name = "2"}};
foreach (MyStruct item in array)
{
Item. Name= "Test";
}

Result: Compile does not pass, hint item is iteration variable, cannot change its member;


3. Iterate over variables as classes

ilist<student> list = db. Students.tolist ();
foreach (Student item in list)
{
item.address = "xxxxxx";
Item.age = 100;
item.id = 1000;
Item.name = "xxxxx";
Item.sex = 1;
}

Result: The compilation passed, and after execution, the properties of item were changed.


Summary: For cases where the iteration variable is a class, foreach can change the properties of the iteration variable during the iteration.



C # foreach Useful method specifically explains

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.