Supporting Material for ‘.NET and Linux’ tech talk

.NET

Code Snippets

Unguarded Code

var registryValue =
    Registry.GetValue("HKEY_CURRENT_USER", "value", "blarg");

Console.WriteLine(registryValue);

This code will raise a type initializer exception if run on a non-Windows system.

It will also generate a compile-time warning: “warning CA1416: This call site is reachable on all platforms. ‘Registry.GetValue(string, string?, object?)’ is only supported on: ‘windows’”

Guarded Code

var registryValue = (OperatingSystem.IsWindows())
    ? Registry.GetValue("HKEY_CURRENT_USER", "value", "blarg")
    : $"Registry does not exist in {Environment.OSVersion}";

Console.WriteLine(registryValue);

This code will run successfully on all platforms. It will not generate a compile-time warning, as the compiler will see that the code is guarded.

Simple IoT Example

This is a simple code example for blinking an LED on a breakout board attached to a Raspberry Pi.

using System;
using System.Device.Gpio;
using System.Threading;

Console.WriteLine("Blinking LED. Press Ctrl+C to end.");
int pin = 18;
using var controller = new GpioController();
controller.OpenPin(pin, PinMode.Output);
bool ledOn = true;
while (true)
{
    controller.Write(pin, ((ledOn) ? PinValue.High : PinValue.Low));
    Thread.Sleep(1000);
    ledOn = !ledOn;
}

Full example is here.