Maybe I'm in the basics, but I'm still studying this C# thing at school. I understand that if I add 1 to max valued Integer, which one is 32 bit, the result will be negative. I read that C# offers checked and unchecked keywords for handling overflows. Checked keyword is something, I've found useful, but how about unchecked keyword? I really can't find not much useful use for unchecked -keyworded block. Is there any? How does the next two approaches differs from each others?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Practice_6
{
class Program
{
static void Main(string[] args)
{
int value = Int32.MaxValue;
value++;
//Approach 1 to make a decision
if (value > Int32.MaxValue) {
//Do something
}
value = Int32.MaxValue;
//Approach 2 to make a decision
unchecked {
value++;
//Do something
}
//What's the difference between these two approaches to handle overflow?
}
}
I'm not quite sure about performance implications of
checked
andunchecked
. In theory,unchecked
should be more performant and it is the default context. Unless you hang around the boundaries of integer types for some kind of special algorithm/business logic etc., usingchecked
is rarely necessary/useful/readable.As I said,
unchecked
is the default context so why do you need anunchecked
keyword? One thing could be to be explicit about the type of a context where there's a high usage ofchecked
contexts. The other is to useunchecked
context insidechecked
context:Your question might be why the default context is unchecked. I guess it's a design choice by Microsoft.
Their difference is that
checked
context checks if there is an overflow for each arithmetic operation and raises an exception if there is an overflow.