Skip to content

tsukiy0's blog

Readable C# Cheatsheet

February 10, 2021

null

  • Explicit check

    if (x is null) { } // x == null
    if (x is not null) { } // x != null
  • Conditional access (elvis operator)

    // `null` if `x` is not present
    x?.y;
    x?[y];
  • Null coallescing

    var x = y ?? 2; // 2 if y is null

Cast

  • Explicit check

    public record Person(string Name);
    if (x is Person) { } // `is` returns boolean
    if (x is Person y) {
    var z = y.Name;
    }
  • Convert

    (int)x; // throws when cannot convert
    x as int; // returns null when cannot convert

Collections

  • Empty array

    IList<int> x = new Array.Empty<int>();
    x.Add(); // throws!
  • Anonymous type

    var x = new {
    Name = "John"
    Age = 21
    };
  • List initializer

    var x = new List<int> { 1, 2, 3 };
    var x = new []{ 1, 2, 3 }; // int[]
    IList<int> x = new []{ 1, 2, 3 };
    x.Add(); // throws!
  • Dictionary initializer

    var x = new Dictionary<string, int> {
    { "one", 1 }
    { "two", 2 }
    };
    var x = new Dictionary<string, int> {
    ["one"] = 1
    ["two"] = 2
    };
  • Collections in object (dont know the name of this)

    public record Box {
    public IList<int> Toys { get; init; }
    }
    new Box {
    Toys = { "gameboy", "twister" }
    };
    public record Box {
    public IDictionary<string, int> Weather { get; init; }
    }
    new Box {
    Weather = {
    ["Adelaide"] = 40,
    ["Melbourne"] = 24
    }
    };

tsukiy0