Skip to content

Instantly share code, notes, and snippets.

@DNA
Created January 17, 2022 16:13
Show Gist options
  • Save DNA/38bf73b94dc5ffc5cab65b47940b0147 to your computer and use it in GitHub Desktop.
Save DNA/38bf73b94dc5ffc5cab65b47940b0147 to your computer and use it in GitHub Desktop.

Revisions

  1. DNA created this gist Jan 17, 2022.
    92 changes: 92 additions & 0 deletions cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,92 @@
    # C# Cheat Sheet

    # Strings

    ```csharp
    "Foo" // string
    'F' // Char
    ```

    ## Interpolations

    ```csharp
    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

    ```csharp
    int qty = 7;

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

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

    ## Operações

    ```csharp
    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

    ```csharp
    int quotient = 7 / 5; // 1
    // └───┴── Both Integers, result is Integer
    ```
    ```csharp
    decimal quotient = 7m / 5; // 1.4
    decimal quotient = 7 / 5.0m; // 1.4
    // └────┴── For fractional results,
    // pass one value as a Decimal
    ```
    ```csharp
    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?)
    ```
    ```csharp
    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