CSharp checked and unchecked

coordonnées GPS:   4°315´S     55°719°E When you create a project in Visual Studio, by default, numbers can be added, multiplied, divided or subtracted in such a way as to create a number too big for the variable that is holding the number.

You can change this at the project level for a Windows exe project by going to project properties, selecting the build tab, clicking the “Advanced” tab and checking the checkbox, “Check for arithmetic overflow/underflow.”

In a web application, you can add a compilerOptions attribute to the compiler element and add the /checked flag.

<compilation debug="true"  compilerOptions="/checked"/>
  <assemblies>
    <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
  </assemblies>
</compilation>

You can also override whatever you set for the default in your compiler options by using the two keywords checked and unchecked in your code.

So, maybe you’ve decided that all of your code should check for overflows and underflows but there is one section of code that you want to allow to overflow or underflow.  You would use unchecked:

int a = int.MaxValue;
int b = int.MaxValue;
unchecked
{
    a = a + b;
}

On the other hand, if you want to make unchecked the default, you can override that by using the keyword checked:

int a = int.MaxValue;
int b = int.MaxValue;
try
{
    a = checked(a + b);
}
catch (OverflowException ofe)
{
    // appropriate handler here
}

Note that if you use checked or that is your default, overflows and underflows will throw an exception, so we’ve added a try/catch block to our code.


Other Related Items:

Cotton Checked Dress 2009 Adora doll outfitCotton Checked Dress 2009 Adora doll outfit
Here is a real cute 20" 2009 Adora doll outfit! This Cotton Checked Dress is the same high quality you are used to with all of the Adora clothes. ... Read More >
The Compleat Option PlayerSecond Edition, Revised and Enlarged. 8vo. 340pp. 44pp. Appendices; 4pp. Index. Shows you how to be a big winner in the options market. Learn how to i... Read More >
All Purpose NetAll Purpose NetThey are specifically designed for koi, surface skimming, and general all-purpose use. Heavy duty aluminum construction, telescoping handle to 6-1/2 . Soft fish safe nylon netting. Sure-grip handle. Aluminum & Nylon Mesh.

Related Post

One Response to “CSharp checked and unchecked”

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor