Skip to content

Instantly share code, notes, and snippets.

@hnh12358
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnh12358/42bee7e9903c163964ab to your computer and use it in GitHub Desktop.
Save hnh12358/42bee7e9903c163964ab to your computer and use it in GitHub Desktop.
using System;
namespace CSharpAdventures
{
class MainClass
{
public static void Main (string[] args)
{
int max = Int32.MaxValue;
Console.WriteLine (CheckedSum(UncheckedSum(max,1),1)); //Doesn't Break.
//Console.WriteLine (UncheckedSum(CheckedSum(max,1),1)); //Will Break!
}
static int CheckedSum(int a, int b)
{
//We can nest the safe/unsafe contexts.
checked {
unchecked {
//We could the keyword as an expression as well.
int temp = unchecked(a + b);
checked {
return a + b;
}
}
}
}
static int UncheckedSum(int a, int b)
{
unchecked {
checked {
int temp = checked(int.MaxValue + 0);
unchecked {
return a + b;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment