30.06.2013 Views

Under the Hood of .NET Memory Management - Simple Talk

Under the Hood of .NET Memory Management - Simple Talk

Under the Hood of .NET Memory Management - Simple Talk

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4: Common <strong>Memory</strong> Problems<br />

Assert.AreEqual(-2, Add(Int32.MaxValue, Int32.MaxValue));<br />

Listing 4.17: The surprising result <strong>of</strong> adding Max Int to itself.<br />

Such overflows are allowed for performance reasons, but <strong>the</strong>y can lead to logical bugs that<br />

would be difficult to track down. You have <strong>the</strong> option to enable <strong>the</strong> check for overflow/<br />

underflow at <strong>the</strong> assembly level, and <strong>the</strong>n every calculation that takes place in that<br />

assembly will be checked. Alternatively, when performance is preferred but some operations<br />

should be checked, use <strong>the</strong> checked keyword to check specific calculations without<br />

incurring this extra cost everywhere.<br />

public int Add(int x, int y)<br />

{<br />

return checked(x + y);<br />

}<br />

Listing 4.18: Explicitly checking a key calculation for overflow.<br />

An OverflowException is now thrown at runtime when <strong>the</strong> above method is called<br />

passing in MaxValue for <strong>the</strong> parameters. If you really want to allow for overflowing, such<br />

as adding Int32.MaxValue to itself, <strong>the</strong>re's a corresponding unchecked keyword.<br />

Strings<br />

Strings are reference types that behave in many ways like a value type. Assignment<br />

and comparison works as you would expect with a value type, because <strong>the</strong>y have value<br />

equality implemented, and sometimes <strong>the</strong>y may even have <strong>the</strong> same reference but, in<br />

general, <strong>the</strong>y will behave more like value types. This is a likely source <strong>of</strong> bugs among<br />

novice programmers, since <strong>the</strong> behavior may not be immediately obvious.<br />

103

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!