Skip to content

Instantly share code, notes, and snippets.

@rstropek
Last active June 6, 2021 07:05
Show Gist options
  • Save rstropek/7423c2a3753cba13c0be181216b9249b to your computer and use it in GitHub Desktop.
Save rstropek/7423c2a3753cba13c0be181216b9249b to your computer and use it in GitHub Desktop.
using System;
using System.Text;
var p1 = new Point(1d, 2d);
// p1.X = 3d; // This does not work because readonly records are immutable
Console.WriteLine(p1);
// Note: At the time of writing, deconstruct can be compiled on sharplab.io, but cannot be executed.
// If you want to run this code on sharplab.io, comment the following statement.
var (x, y) = p1; // Deconstruction works similar to record classes.
var p2 = p1 with { X = 4d }; // We can use the with keyword
// Readonly leads to an immutable struct
// Note that you can use the property: syntax to apply attributes
// or you can apply attributes to manually declared properties.
readonly record struct Point(double X, [property: JsonPropertyName("y")] double Y)
{
// It is possible to manually declare property.
[JsonPropertyName("x")]
public double X { get; init; } = X;
// Although PrintMembers is private, we can add a custom implementation.
// C# considers the members as "matching" if signature matches.
private bool PrintMembers(StringBuilder sb)
{
sb.Append($"X/Y = {X}/{Y}");
return true;
}
}
// Simulate use of System.Text.Json
[AttributeUsage(AttributeTargets.Property)]
public class JsonPropertyNameAttribute : Attribute
{
public JsonPropertyNameAttribute(string name) { /* ... */ }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment