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.

Related Post

One Response to “CSharp checked and unchecked”

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear