Skip to content

Instantly share code, notes, and snippets.

View ufcpp's full-sized avatar

Nobuyuki Iwanaga ufcpp

View GitHub Profile
unsafe
{
Circle circle = new() { Radius = 1 };
Rectangle rectangle = new() { Width = 2, Height = 3 };
Rectangle square = new() { Width = 2, Height = 2 };
Console.WriteLine(Algorithm.AreaRatio(0, &circle));
Console.WriteLine(Algorithm.AreaRatio(1, &rectangle));
Console.WriteLine(Algorithm.AreaRatio(1, &square));
for (uint i = 0; i < 12; i++)
{
Console.WriteLine(format(i));
}
for (uint i = 15; i < 120; i+=7)
{
Console.WriteLine(format(i));
}
Console.WriteLine(format(1234));
@ufcpp
ufcpp / CovariantDictionary.cs
Last active November 22, 2023 12:14
IReadOnlyDictionary の TValue に out つけれないの毎度つらい
using System.Collections;
using System.Runtime.CompilerServices;
var d = new Dictionary<int, string> { { 1, "one" }, { 2, "two" } };
ICovariantDictionary<int, string> cd = d.AsCovariant();
// TValue が out なので string → object 代入可能。
ICovariantDictionary<int, object> id = cd;
foreach (var (k, v) in id)
namespace TimeProviderExtension;
public class PausableTimeProvider(TimeProvider innerProvider) : TimeProvider
{
public PausableTimeProvider() : this(System) { }
private long _pausedTimestamp = innerProvider.GetTimestamp();
private long _offsetTimestamp = 0;
private DateTimeOffset _pausedUtcNow = innerProvider.GetUtcNow();
private TimeSpan _offsetUtcNow = default;
@ufcpp
ufcpp / RefImplicitCast.cs
Created September 21, 2023 13:39
Unsafe.AsRef implicit operator
using System.Runtime.CompilerServices;
var p = new Private();
Console.WriteLine(p.Value); // 0
Accessor r = p; // implicit cast で p の参照が r に渡る。
r.Value = 1;
Console.WriteLine(p.Value); // 書き変わってる。
// PrivateProxy 触りつつ、
@ufcpp
ufcpp / PCParamegers.cs
Created September 15, 2023 08:22
プライマリコンストラクター引数のキャプチャ
class A(int x)
{
int _x = x; // これはキャプチャしない。
}
class B(int x)
{
public int X { get; } = x; // これもキャプチャしない。
}
@ufcpp
ufcpp / Program.cs
Created July 26, 2023 02:07
default リテラルのオーバーロード解決?
X.M(0); // 整数リテラルの自然な型は int
X.M(default); // でも、 default は「サイズが小さい型優先」っぽい
// そういう仕様?意図的?
class X
{
public static void M(int i32) { }
public static void M(short i16) { }
}
@ufcpp
ufcpp / StringComparison.cs
Created June 14, 2023 10:51
ひどい。
using System.Globalization;
using System.Text.RegularExpressions;
using static System.Console;
var s1 = "a\u0301"; // á = a + ́
var s2 = "\u00e1"; // á
// たとえ InvariantCulture でも。
// <InvariantGlobalization>false</InvariantGlobalization> な限り。
// (↑true のときは、StringComparison.Default が Ordinal になる効果もあり。)
using System.Buffers.Text;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
var x = 0x12345678;
Console.WriteLine($"{x.Hex()}");
public static class Format
{
public static AsciiBuffer8 Hex(this int x)
using System.Buffers.Binary;
var x = 0x12345678;
Console.WriteLine($"{x:X}");
Console.WriteLine($"{x.Little()}");
static class LittleEndianExtensions
{
public static LittleEndianInt32 Little(this int x) => new(x);