Hmobius Notes |||

C# Coding Standards, Mid 2019 Edition

Notes from Effective C#, 3e and More Effective C#, 2e, both by Bill Wagner.

  1. Use var except when differentiating between number types.
  2. Use public static readonly T instead of public const T.
  3. Use properties instead of data fields. Properties can also be private, protected, internal, virtual, implicit, explicit, etc.
  4. Assume default access level for methods and properties is private. Promote to protected, internal or public as and when required.
  5. Ensure that 0 (zero) is a valid state fr value types. Especially enums.
  6. Use is or as where possible rather than casts.
  7. Use interpolated strings like $"The value is {Math.Pi.ToString()}" instead of string.Format().
  8. Use membership initializers like var myList = new List<string>(); rather than assignment statements after variable is declared.
  9. Minimize duplicate initialisation code by having contructors call other constructors.
public MyClass() : this(0, string.Empty) {}
public MyClass(int  count, string value) { \\things occur  }
  1. Prefer iterator methods to returning collections.
public static IEnumerable<char> GenerateAlphabet()
    var letter = 'a';
    while (letter < 'z')
        yield return letter;
  1. Try to use LINQ queries instead of c# loops. Query syntax keywords are from, where, select, orderby (descending). Or you could use the method-style of LINQ depending on readability. The point is to try not to use for, while, do while or foreach. For example
(from n in Enumerable.Range(0, 100)
 select n * n).ToArray();

myList.ForAll<string>(n => Console.WriteLine(n));
  1. Don’t call ToList() or ToArray() to queries and draw the whole resultset into memory until absolutely necessary. Or rather, go for lazy rather than eager evaluation where possible.
  2. Use Single() and First() to enforce semantic expectations on queries.
    • Single() returns exactly one element. If zero or more than one are returned, it throws an exception.
    • SingleOrDefault() returns exactly one element. If zero, returns null. Otherwise, it throws an exception.
    • Use First() or FirstOrDefault() if you are expecting more than one results but want a specific one.
Up next Inheritance Tracks Inheritance tracks is a podcast from Radio 4. Each week, a known person talks through a piece of music they inherited from their parents and a piece Visual Studio Code Setup Being a quick rundown of how I currently have VS Code setup. Candara is my coding font of choice. Monospace  glyphed fonts are not necessary.
Latest posts Standard Grixis Dredge in ELD Handy LINQ stuff Visual Studio Code Setup C# Coding Standards, Mid 2019 Edition Inheritance Tracks Simic Flash in M20