Created
April 10, 2015 02:35
-
-
Save hnh12358/cb2149894511f6e9ecf0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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