Skip to content

Instantly share code, notes, and snippets.

@DNA
Created January 17, 2022 16:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DNA/38bf73b94dc5ffc5cab65b47940b0147 to your computer and use it in GitHub Desktop.
Save DNA/38bf73b94dc5ffc5cab65b47940b0147 to your computer and use it in GitHub Desktop.
Personal annotations as I learn C#

C# Cheat Sheet

Strings

"Foo" // string
'F'   // Char

Interpolations

Console.WriteLine("c:\source\repos\foo");    // c:sourcereposfoo ⚠️
Console.WriteLine("c:\\source\\repos\\foo"); // c:\source\repos\foo
Console.WriteLine(@"c:\source\repos\foo");   // c:\source\repos\foo

string name = "foo";
string path = $"C:\\source\\repos\\{name}";
Console.WriteLine(path);                       // c:\source\repos\foo
Console.WriteLine($@"C:\source\repos\{name}"); // c:\source\repos\foo

Numbers

Inplicity type conversion

int qty = 7;

Console.WriteLine("Total: " + qty + 7 + " items");
//                             └─ Convertions before concatenation
// Total: 77 items
int qty = 7;

Console.WriteLine("Total: " + (qty + 7) + " items");
//                            └─ Use parentesis to change the order
// Total: 14 items

Operações

int sum        = 7 + 5; // 12
int difference = 7 - 5; // 2
int product    = 7 * 5; // 35
int quotient   = 7 / 5; // 1 ⚠️
int modulus    = 7 % 5; // 4

Integer vs Float vs Decimal

int     quotient = 7 / 5;  // 1
//                 └───┴── Both Integers, result is Integer
decimal quotient = 7m / 5;    // 1.4
decimal quotient = 7  / 5.0m; // 1.4
//                 └────┴── For fractional results,
//                          pass one value as a Decimal
decimal quotient = 7.0 / 5;
//                  └─ This will fail!
// error CS0266:
// Cannot implicitly convert type 'double' to 'decimal'.
// An explicit conversion exists (are you missing a cast?)
int     first    = 7;
int     second   = 5;
decimal quotient = (decimal) first / second;
//                     └─ When using variables,
//                        just cast the needed type!

Operation Order

In math, PEMDAS is an acronym remember the order operations are performed:

- Parentheses    ── Whatever is inside performs first)
- Exponents      ── ⚠️
- Multiplication ╮
- Division       ├─ From left to right
- Addition       │
- Subtraction    ╯

⚠️ There's no exponent operator in C#, use System.Math.Pow() instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment