File tree 3 files changed +58
-0
lines changed
CSharp Code Samples/CodeSamples
3 files changed +58
-0
lines changed Original file line number Diff line number Diff line change 105
105
<Compile Include =" Useful\GarbageCollectionSample.cs" />
106
106
<Compile Include =" Useful\LinqSample.cs" />
107
107
<Compile Include =" Classes\ClassAndMethodNamesSample.cs" />
108
+ <Compile Include =" Useful\OverflowCheckSample.cs" />
108
109
</ItemGroup >
109
110
<ItemGroup >
110
111
<None Include =" App.config" />
Original file line number Diff line number Diff line change @@ -149,6 +149,11 @@ static void Main(string[] args)
149
149
enumSample . Execute ( ) ;
150
150
#endregion
151
151
152
+ #region Arithmetic Overflow
153
+ var overflowCheckSample = new OverflowCheckSample ( ) ;
154
+ overflowCheckSample . Execute ( ) ;
155
+ #endregion
156
+
152
157
Console . WriteLine ( ) ;
153
158
Console . WriteLine ( "End Code Samples" ) ;
154
159
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments