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, size<strong>of</strong>(Char));<br />

Assert.AreEqual(1, Marshal.SizeOf(new Char()));<br />

Listing 4.15: Comparing <strong>the</strong> sizes <strong>of</strong> chars in managed and unmanaged code.<br />

Overflow checking<br />

The .<strong>NET</strong> framework can do automatic arithmetic overflow checking to ensure that<br />

calculations are not corrupted by overflowing <strong>the</strong> values in <strong>the</strong> underlying type system. By<br />

default this is disabled in C#. Ironically, this is enabled by default for a VB.<strong>NET</strong> project,<br />

but <strong>the</strong>re is little risk from disabling it in most cases. As you will see below, <strong>the</strong> right set <strong>of</strong><br />

conditions have to be met to even have a risk <strong>of</strong> an overflow.<br />

Figure 4.2: You can explicitly enable/disable overflow checking.<br />

The maximum value <strong>of</strong> System.Int32 is 2,147,483,647. What is <strong>the</strong> value when you add<br />

Int32.MaxValue to itself? Well, <strong>the</strong> compiler is smart enough to throw a compile-time<br />

error: The operation overflows at compile time in checked mode. Of course, <strong>the</strong> compiler can<br />

easily be confused. Let's add a method (see Listing 4.16).<br />

101

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

Saved successfully!

Ooh no, something went wrong!