Skip to content

Instantly share code, notes, and snippets.

@ssippe
Created December 14, 2020 01:44
Show Gist options
  • Save ssippe/1af94d024c542c02c43acd8b08e8c289 to your computer and use it in GitHub Desktop.
Save ssippe/1af94d024c542c02c43acd8b08e8c289 to your computer and use it in GitHub Desktop.
namespace cs9test
{
// @jbogard "it looks like the "immutable-by-default" behavior of C# 9 records is really only with the compact positional syntax, not with just the "record" keyword"
// https://twitter.com/jbogard/status/1321120266676850688
/// <summary>
/// immutable with compact positional syntax
/// </summary>
public record Person(string FirstName, string LastName);
/// <summary>
/// immutable with nominal syntax
/// </summary>
public record Person2
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
/// <summary>
/// mutable with nominal syntax
/// </summary>
public record Person3
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
var p1 = new Person("James", "Bond");
// var p1a = new Person { FirstName = "James", LastName = "Bond" }; error CS7036: There is no argument given that corresponds to the required formal parameter 'FirstName' of 'Person.Person(string, string)'
var p1b = new Person(LastName: "Bond", FirstName:"James");
var p2 = new Person2{FirstName="James", LastName="Bond"};
var p3 = new Person3 { FirstName = "James", LastName = "Bond" };
// immuatable / mutable
// p1.FirstName = "Blah"; // Error CS8852 Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
// p2.FirstName = "Blah"; // error CS8852: Init-only property or indexer 'Person2.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
p3.FirstName = "Blah"; // ok
Console.WriteLine($"Hello World! {p1} {p2} {p3} {p1b}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment