C# Best Practices: Improving on the Basics

0

Category :

Null Reference Check - Null Conditional Operator

product?.Option?.Name

Nullable Types

help distinguish default and "not set" values

Static Class

Container for Utility methods logging + email

Read-only properties

set on intialisation or constructor and not changed.

Expression based Properties

using lambda operator => public string FullName => FirstName + " " + LastName;

Auto-Implemented Properties

simple properties, no additional get/set code necessary

Validate Incoming Params - "Guard clauses"

 if(product == null) throw new ArgurmentNulException(nameof(product));
Guard clauses should also be tested.
 [ExpectedException(typeof(ArgumentNullException))]

Method Chaining - Optional Params

One method overload calls another method overload to prevent repeated code.
public Result PlaceOrder(Product product, int quantity)
{
   return PlaceOrder(product, quantity, null, null);
}

public Result PlaceOrder(Product product, int quantity, DateTimeOffset? deliverBy)
{
   return PlaceOrder(product, quantity, deliverBy, null);
}

public Result PlaceOrder(Product product, int quantity, DateTimeOffset? deliverBy, string instructions)
{
   // all of code here
}

Expression-bodied Methods

Syntax shortcut for single statement methods that return a value. Avoid when:
Guard clauses are necessary.
Exception handling necessary.
public decimal CalculateSuggestedPrice(decimal markupPercent)
{
 return this.Cost + (this.Cost * markupPercent / 100);
}

public decimal CalculateSuggestedPrice(decimal markupPercent) =>
 this.Cost + (this.Cost * markupPercent / 100);


my thanks to:
https://app.pluralsight.com/library/courses/csharp-best-practices-improving-basics/table-of-contents