The Value Type struct traps in foreach, structforeach

Source: Internet
Author: User

The Value Type struct traps in foreach, structforeach

Recently, I stepped on a pitfall. To optimize the code, I changed the class to struct. The result showed that the original initialization statement was not run as expected. The pseudocode is as follows:

Public struct A {bool _ isActive; public void Init (bool isActive) {_ isActive = isActive ;}}
Public A [] _ arrayA; // call the following foreach A in _ arrayA) {a. Init ();}

It looks like it can meet expectations, but it is not actually.

In foreach, a temporary variable is usually copied. The difference is that the value type copies a new value type and the new value type changes, it is not the content in the array. However, the referenced content copied from the reference type still references the reference of the same content. Therefore, all the operations performed by using the newly copied reference will be applied to the expected content.
Therefore, you still need to use the for loop to replace foreach.

For (int I = 0; I <_ arrayA. Length; I ++) {_ arrayA [I]. Init ();}

If you want to learn more about this, we recommend the following articles:

Http://stackoverflow.com/questions/5663783/in-net-using-foreach-to-iterate-an-instance-of-ienumerablevaluetype-will-c

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.