Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does checked and unchecked work on conversion in C#

Tags:

c#

My question is about this code in a C# console programming I ask it with an example:

This code is impossible :

byte sum = (byte)(150 + 150); //impossible

but this code is possible :

byte sum = unchecked((byte)(150 + 150)); //possible

My question is: how does unchecked work? I mean how does UNCHECKED make this code possible?

like image 695
Hava Darabi Avatar asked Dec 25 '22 23:12

Hava Darabi


1 Answers

All unchecked means is if the value overflows (crosses over the MaxValue or MinValue boundary) no error is thrown and it allows the wrap-around to happen.

The byte.MaxValue is 255, 150 + 150 is 300. By allowing the overflow, it crosses over the 255 boundary and and starts counting again from byte.MinValue (0 in this case) to reach a final value of 44 ((150 + 150) - 256 = 44)

like image 83
Scott Chamberlain Avatar answered Jan 12 '23 12:01

Scott Chamberlain