Skip to content

Instantly share code, notes, and snippets.

@hnh12358
Created April 10, 2015 02:35
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/cb2149894511f6e9ecf0 to your computer and use it in GitHub Desktop.
Save hnh12358/cb2149894511f6e9ecf0 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;
//[1]
Console.WriteLine (CheckedSum(UncheckedSum(max,1),1)); //Doesn't Break.
//Console.WriteLine (UncheckedSum(CheckedSum(max,1),1)); //Will Break!
//[2]
checked {
Console.WriteLine(Unchecked (() => max + 1));
}
}
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;
}
}
}
}
static int Unchecked (Func<int> code) {
return code.Invoke ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment