none
C# unchecked keyword - dangerous? RRS feed

  • Question

  • Hi,

    Is there danger of memory corruption or leak if I use the unchecked keyword?  

    For example, if I have code that does this:

    int x = int.MaxValue;
    unchecked {
     x = x + 10;
    }

    Is the worst case here that the value of x wraps and gives an unexpected value, or is there potentially more dangerous consequences that can arise from doing this?

    Thanks

    Mark


    Monday, January 20, 2020 8:01 PM

All replies

  • No problem here. The only effect of unchecked in this example is that x will "wrap around" on its binary value, but nothing will be corrupted other than the value of x itself.
    Monday, January 20, 2020 9:01 PM
    Moderator
  • Seems that the issue would be if an unexpected value is produced that may cause issues with what the variable is used for else no issues.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, January 20, 2020 10:22 PM
    Moderator