Skip to content

Instantly share code, notes, and snippets.

@bitbonk
Last active January 24, 2020 12:59
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 bitbonk/323263bdacd5e495b0e04573b28c264b to your computer and use it in GitHub Desktop.
Save bitbonk/323263bdacd5e495b0e04573b28c264b to your computer and use it in GitHub Desktop.
Record and discriminated unions in C# 9
public class Person
{
public initonly string Firstname { get; }
public initonly string Lastname { get; }
};
enum class ByteOrBool { byte Y; bool B;}
enum class MixedType
{
Person P;
ByteOrBool U;
}
var bart = new Person()
{
Firstname = ”Bart”;
Lastname = “Simpson”;
};
var lisa = bart with { Firstname = "Lisa" };
var unionRecord = new MixedType.P(bart);
var unionType1 = new MixedType.U(B true);
var unionType2 = new MixedType.U(Y 0x42);
@oocx
Copy link

oocx commented Jan 24, 2020

Looks great!

it would also be nice if it can infer types:
Person p = new { Firstname = "Homer", Lastname = "Simpson" };

@bitbonk
Copy link
Author

bitbonk commented Jan 24, 2020

I agree. I think they are at least considering to allow omitting the „new“ keyword.

All the design proposals are here https://github.com/dotnet/csharplang/tree/master/proposals
(I am in no way involved in the design, just wanted to understand the current status and made this gist in the process.)

@JeroMiya
Copy link

What happened to primary constructors? That's a lot of code in place of just class Person(string FirstName, string LastName)

@bitbonk
Copy link
Author

bitbonk commented Jan 24, 2020

Good question. It seems that primary constructors are still part of the overarching records proposal but it looks like there are quite some issues that need to be worked out.

There is also a wild discussion about it here: dotnet/csharplang#2691

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment