Value type trap for struct in foreach

Source: Internet
Author: User

Recently stepped on a hole, in order to optimize the code, the class changed to a struct, the results found that the original initialization statement did not expect to run, pseudo-code as follows:

 Public struct a{    bool  _isactive;      Public void Init (bool  isActive)    {        = isActive;    }}
    Public//Call the following foreach in _arraya) {a.init ()    ;}

It looks as if it can be expected, but it's not.

In foreach, a temporary variable is usually copied, except that the value type, which is copied with a new value type, is also the new value type, not the contents of the array, but the reference type copies the reference to the same content. So the use of the new copy of the reference will be applied to the content we expect.
Therefore, you should replace foreach with a For loop.

 for (int0; i < _arraya.length; i++) {    _arraya[i]. Init ();}

If you want to know more about these, the following articles are recommended:

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

Value type trap for struct in foreach

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.