C# snippets That Make You Go Hmmm...
All snippets are linked to their original creators (or the people I found them from). I don't take any credit, just collating fun bits! Most also have SharpLab.io links so you can see them in action yourself.
{}
using System;
unsafe class Program
{
delegate void bar(int* i);
static Index ƛ(bar β) => default;
static void Main(string[] args)
{
int[] ω = { };
int Ʃ = 42;
int? Φ = 10;
var ϼ = ω;
ϼ=ω[ƛ(β:Δ=>Φ??=ω[^++Ʃ]/Ʃ|*&Δ[-0%Ʃ]>>1^Φ??0!&~(δ:Ʃ,^Φ..).δ)..(1_0>.0?Ʃ:0b1)];
}
}
using System;
using System.IO;
Console.WriteLine(Path.DirectorySeparatorChar); // prints '\'
var f = (in char x) => { /* can't modify 'x' here */ };
f = (ref char x) => { x = 'A'; }; // but can here!
f(Path.DirectorySeparatorChar);
Console.WriteLine(Path.DirectorySeparatorChar); // prints 'A'
// Exactly the same as Year, Month, Day properties, except computing all of
// year/month/day rather than just one of them. Used when all three
// are needed rather than redoing the computations for each.
//
// Implementation based on article https://arxiv.org/pdf/2102.06959.pdf
// Cassio Neri, Lorenz Schneiderhttps - Euclidean Affine Functions and Applications to Calendar Algorithms - 2021
internal void GetDate(out int year, out int month, out int day)
{
// y400 = number of whole 400-year periods since 3/1/0000
// r1 = day number within 400-year period
(uint y400, uint r1) = Math.DivRem(((uint)(UTicks / TicksPer6Hours) | 3U) + 1224, DaysPer400Years);
ulong u2 = (ulong)Math.BigMul(2939745, (int)r1 | 3);
ushort daySinceMarch1 = (ushort)((uint)u2 / 11758980);
int n3 = 2141 * daySinceMarch1 + 197913;
year = (int)(100 * y400 + (uint)(u2 >> 32));
// compute month and day
month = (ushort)(n3 >> 16);
day = (ushort)n3 / 2141 + 1;
// rollover December 31
if (daySinceMarch1 >= March1BasedDayOfNewYear)
{
++year;
month -= 12;
}
}
using System;
using System.Collections.Generic;
var list = new List<int>{1, 2, 3, 4};
IReadOnlyList<int> readonlyList = list;
// error CS1061: 'IReadOnlyList<int>' does not contain a definition for 'Add'...
// readonlyList.Add(5);
// Works as expected
((List<int>)readonlyList).Add(5);
// 5
Console.WriteLine(readonlyList.Count);
async async async(async async) =>
await async;
[async, async<async>] async async async([async<async>, async] (async async, async) async)
=> await async.async;
using System;
float x = 0.4f;
float y = 0.6f;
Console.WriteLine((double)x + (double)y == 1); // False
Console.WriteLine((float)((double)x + (double)y) == 1); // True
Note this is for .NET Framework.
try {}
finally
{
if (!m_canceled)
{
m_canceled = true;
TimerQueue.Instance.DeleteTimer(this);
}
}
An unsigned number bug in Environment.TickCount
in a specific situation in a threadpool prevent more threads from being added to the pool.
global using var = dynamic;