Posts

Nullable reference types

C# now includes the concept of a "nullable" reference type. The name is a bit confusing, because reference type variables were always nullable. What they really should have called it is "non-nullable", since that's what's different now. In the past, you could declare a string variable or property, and it was perfectly valid to assign that to null. So if you're going to use it, you need to do a null-check to avoid exceptions. Now, if you turn on the flag in your project, the compiler will help you avoid null exceptions, by forcing you to define when a variable or property is allowed to be null, and there are warnings or errors to alert you when you're trying to potentially set a non-nullable variable to null. View code on GitHub

C# Records

Image
C# records are a new way of defining reference types that use value equality. They're very helpful when you need an immutable data type, saving you from having to write readonly properties and overriding a bunch of equality methods. For example, here's an immutable class definition with value equality and a nicely formatted string output: public class TeamClass { private readonly string _name ; private readonly int _yearFormed ; public TeamClass ( string name , int yearFormed ) = > ( _name , _yearFormed ) = ( name , yearFormed ) ; public string Name = > _name ; public int YearFormed = > _yearFormed ; public override string ToString ( ) = > $ " TeamClass {{ Name = {Name}, YearFormed = {YearFormed} }} " ; public override bool Equals ( object obj ) { return obj is TeamClass otherTeam && Name = = otherTeam . Name && Year

Number Formats in .NET

Image
You can easily format numbers using built-in standard or custom format strings. Depending on your environment, you may want complete control over number formats, or you may want to leave it up to the user's locale. View code on GitHub

Mustache in .NET

Image
Mustache is a really simple templating engine, and a good choice for building HTML. Here's an example using the Stubble package in .NET. View code on GitHub

Update with Output in SQL Server

Image
If you're doing an update, and need information on the records you're updating, you can do it all in a single command. This video gives you an example using a CTE, where you update, and also pull data down from the records that you're updating, all in a single command. View code on GitHub

SQL Cursors

Image
Most of the time, you can use regular queries to accomplish your needs in a SQL database. There are plenty of interesting design patterns to work with sets of data, but once in awhile, you need the flexibility of a cursor. Here's an example of a straightforward read only cursor. View code on GitHub

Writing CSV with CsvHelper

Image
The CsvHelper library includes a very easy way to transform .NET objects into properly formatted CSV. To read CSV, check out my previous post . View code on GitHub