Skip to content

Instantly share code, notes, and snippets.

Avatar

Rich Lander richlander

View GitHub Profile
@richlander
richlander / Program.cs
Created Oct 12, 2021
const interpolated string example
View Program.cs
const string Bar = "Bar";
const string DoubleBar = $"{Bar}_{Bar}";
WriteLine(DoubleBar);
View ClimateControl.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@richlander
richlander / Program.cs
Created Oct 11, 2021
readonly record struct example
View Program.cs
Battery battery = new("CR2032", 0.235, 100);
WriteLine(battery);
while (battery.RemainingCapacityPercentage > 0)
{
Battery updatedBattery = battery with {RemainingCapacityPercentage = battery.RemainingCapacityPercentage - 1};
battery = updatedBattery;
}
@richlander
richlander / ClimateControl.csproj
Created Oct 11, 2021
Extended properties example
View ClimateControl.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@richlander
richlander / Program.cs
Last active Oct 21, 2021
Record struct example
View Program.cs
Battery battery = new("CR2032", 0.235, 100);
WriteLine(battery);
while (battery.RemainingCapacityPercentage > 0)
{
battery.RemainingCapacityPercentage--;
}
WriteLine(battery);
View SwitchStatementMapper.cs
namespace XUnitTestProject
{
using Xunit;
public static class SwitchStatementMapper
{
// Don't judge me, it's only for educational purposes :)
public static bool Map(string str) => str switch
{
"true" => true,
@richlander
richlander / modernizing-csharp9.md
Last active May 13, 2022
Modernizing a codebase for C# 9
View modernizing-csharp9.md

Modernizing a codebase for C# 9

There are lots of cases that you can improve. The examples use nullable reference types, but only the WhenNotNull example requires it.

Use the property pattern to replace IsNullorEmpty

Consider adopting the new property pattern, wherever you use IsNullOrEmpty.

string? hello = "hello world";
@richlander
richlander / Program.cs
Last active Dec 7, 2020
Get Weather Forecast -- with records
View Program.cs
using System;
using System.Net.Http;
using System.Net.Http.Json;
string serviceURL = "https://localhost:5001/WeatherForecast";
HttpClient client = new();
Forecast[] forecasts = await client.GetFromJsonAsync<Forecast[]>(serviceURL);
foreach(Forecast forecast in forecasts)
{