Skip to content

Instantly share code, notes, and snippets.

@richlander
Last active September 12, 2020 23:37
Show Gist options
  • Save richlander/2c63df7e23d038145eb5d22c4b8dbdc2 to your computer and use it in GitHub Desktop.
Save richlander/2c63df7e23d038145eb5d22c4b8dbdc2 to your computer and use it in GitHub Desktop.
Records and nullability
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
Author lord = new Author("Karen Lord")
{
Website = "https://karenlord.wordpress.com/",
RelatedAuthors = new()
};
lord.Books.AddRange(
new Book[]
{
new Book("The Best of All Possible Worlds", 2013, lord),
new Book("The Galaxy Game", 2015, lord)
}
);
lord.RelatedAuthors.AddRange(
new Author[]
{
new ("Nalo Hopkinson"),
new ("Ursula K. Le Guin"),
new ("Orson Scott Card"),
new ("Patrick Rothfuss")
}
);
Console.WriteLine($"Author: {lord.Name}");
Console.WriteLine($"Books: {lord.Books.Count}");
Console.WriteLine($"Related authors: {lord.RelatedAuthors.Count}");
public record Author(string Name)
{
private List<Book> _books = new();
public List<Book> Books => _books;
public string? Website {get; init;}
public string? Genre {get; init;}
public List<Author>? RelatedAuthors {get; init;}
}
public record Book(string name, int Published, Author author);
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment