Skip to content

Instantly share code, notes, and snippets.

@hnh12358
Last active Aug 29, 2015
Embed
What would you like to do?
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