Skip to content

Commit 1122dc4

Browse files
author
ahotko
committed
Added checked/unchecked snippet
1 parent 1ab7b7e commit 1122dc4

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

CSharp Code Samples/CodeSamples/CodeSamples.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@
105105
<Compile Include="Useful\GarbageCollectionSample.cs" />
106106
<Compile Include="Useful\LinqSample.cs" />
107107
<Compile Include="Classes\ClassAndMethodNamesSample.cs" />
108+
<Compile Include="Useful\OverflowCheckSample.cs" />
108109
</ItemGroup>
109110
<ItemGroup>
110111
<None Include="App.config" />

CSharp Code Samples/CodeSamples/Program.cs

+5
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,11 @@ static void Main(string[] args)
149149
enumSample.Execute();
150150
#endregion
151151

152+
#region Arithmetic Overflow
153+
var overflowCheckSample = new OverflowCheckSample();
154+
overflowCheckSample.Execute();
155+
#endregion
156+
152157
Console.WriteLine();
153158
Console.WriteLine("End Code Samples");
154159

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
using System;
2+
3+
namespace CodeSamples.Useful
4+
{
5+
public class OverflowCheckSample : SampleExecute
6+
{
7+
public override void Execute()
8+
{
9+
Title("OverflowCheckSampleExecute");
10+
11+
int firstValue;
12+
int secondValue;
13+
14+
int maxValue = 2147483647;
15+
const int maxInt = int.MaxValue;
16+
17+
//do not check for overflow
18+
unchecked
19+
{
20+
firstValue = 2147483647 + 100;
21+
}
22+
Console.WriteLine($"Unchecked sum 1 (in block) (overflow) = {firstValue}");
23+
//...or...
24+
firstValue = unchecked(maxInt + 100);
25+
26+
Console.WriteLine($"Unchecked sum 1 (inline) (overflow) = {firstValue}");
27+
28+
//unchecked by default at compile time and run time because it contains variables
29+
secondValue = maxValue + 100;
30+
Console.WriteLine($"Unchecked sum 2 (variabled added) (overflow) = {secondValue}");
31+
32+
//catch overflow at run time
33+
try
34+
{
35+
checked
36+
{
37+
secondValue = maxValue + 100;
38+
}
39+
Console.WriteLine($"Unchecked sum 2 (in block) (overflow) = {secondValue}");
40+
//...or...
41+
secondValue = unchecked(maxValue + 100);
42+
Console.WriteLine($"Unchecked sum 2 (inline) (overflow) = {secondValue}");
43+
}
44+
catch (Exception e)
45+
{
46+
Console.WriteLine($"Exception '{e.GetType().Name}' with message '{e.Message}' was thrown.");
47+
}
48+
49+
Finish();
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)