Skip to content

Instantly share code, notes, and snippets.

@dchw
dchw / RoundingExamples.cs
Created April 12, 2014 08:55
Different types of rounding and casting, and how they affect decimals.
var numsToRound = new []{0.5, 1.5, 2.5, 3.5, 4.5};
Console.WriteLine("Banker|Away|Convert|Cast");
foreach(var num in numsToRound)
{
var toEven = Math.Round(num);
var awayFromZero = Math.Round(num, MidpointRounding.AwayFromZero);
var convert = Convert.ToInt32(num);
var cast = (int)num;
Console.WriteLine(String.Format(" {0} | {1} | {2} | {3} ", toEven, awayFromZero, convert, cast));
@dchw
dchw / EnumeratedTricks4.cs
Created April 12, 2014 07:24
Applications of some of the enum tricks
public class HeroWithPowers
{
public Superhero Hero {get; set;}
public Powers Powers {get; set;}
}
void Main()
{
var heros = new List<HeroWithPowers>
{
@dchw
dchw / EnumeratedTricks3.cs
Created April 12, 2014 07:21
Enum extension method example
public static class SuperheroEx
{
public static string Name(this Superhero superhero)
{
return Enum.GetName(typeof(Superhero), superhero);
}
}
@dchw
dchw / EnumeratedTricks2.cs
Created April 12, 2014 07:19
Arbitrary assignment of values to enum typed variables.
var hero = (Superhero)42;
var powers = Powers.Looks | Powers.Money | Powers.Smart
@dchw
dchw / Enumerated Tricks1.cs
Created April 12, 2014 07:16
Using left shit to achieve a continuous range of values, while still using bit fields appropriately.
[Flags]
public enum Powers : byte
{
Speed = 1,
Looks = 1 << 1,
Money = 1 << 2,
Smart = 1 << 3,
None = 1 << 4
}
@dchw
dchw / (Un)ReservedKeywords2.cs
Last active August 29, 2015 13:57
Using the 'switch' keywords as a descriptive way to fake switching on types in C#.
var @switch = new Dictionary<Type, Action>
{
{typeof(CSharp), () =>
{
Console.WriteLine("<3");
}},
{typeof(Rainbow), () =>
{
Console.WriteLine("20% Cooler");
}},
@dchw
dchw / (Un)ReservedKeywords.cs
Last active August 29, 2015 13:57
Using keywords as variable names
var @null = "HEY";
var @if = "WHAT R U DOIN";
var @object = "PLZ STAHP";
Console.WriteLine(String.Format("{0} {1} {2}", @null, @if, @object));