Skip to content

Instantly share code, notes, and snippets.

@MichalBrylka
Last active September 25, 2023 17:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichalBrylka/417672620d1305de4a6db68698302544 to your computer and use it in GitHub Desktop.
Save MichalBrylka/417672620d1305de4a6db68698302544 to your computer and use it in GitHub Desktop.
Creating and using C# 9.0 records
using System;
using RecordsProducer;
var lizard1 = new Reptile(Habitat.Terrestrial) { Name = "Agama" };
var lizard2 = new Reptile(Habitat.Terrestrial) { Name = "Agama" };
//use <LangVersion>latest</LangVersion>
var lizard3 = lizard1 with { Name = "Komodo dragon", Habitat = Habitat.Terrestrial };
var vertebrateLizard = new Vertebrate() { Name = "Agama" };
Console.WriteLine("Equal:" + (vertebrateLizard == lizard1));
Console.WriteLine(lizard1.ToString() + " == Reptile { Name = Agama, Habitat = Terrestrial }");
Vertebrate vertebrate = new Reptile(Habitat.Terrestrial) { Name = "Agama" };
Vertebrate other = vertebrate with { Name = "Komodo dragon" };
Console.WriteLine(other.ToString());
Console.WriteLine("IsInitOnly:" +typeof(Vertebrate).GetProperty(nameof(Vertebrate.Name)).IsInitOnly());
using System;
using System.Linq;
using System.Reflection;
namespace RecordsProducer
{
public enum Habitat
{
Terrestrial,
Aquatic,
Amphibian,
}
public record Vertebrate(string Name)
{
public Vertebrate() : this("") { }
}
public record Reptile(Habitat Habitat) : Vertebrate
{
}
public static class RecordsHelper
{
public static bool IsInitOnly(this PropertyInfo property) =>
property.CanWrite && property.SetMethod is var setter
&& setter.ReturnParameter.GetRequiredCustomModifiers() is var reqMods && reqMods.Length > 0
&& Array.IndexOf(reqMods, typeof(System.Runtime.CompilerServices.IsExternalInit)) > -1;
}
}
#if NETSTANDARD2_0
namespace System.Runtime.CompilerServices
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static class IsExternalInit { }
}
#endif
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net48;net5.0</TargetFrameworks>
<LangVersion>9.0</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RecordsProducer\RecordsProducer.csproj" />
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net5.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
</PropertyGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment