C#
Magic Methods Curiosity
The C# language includes a number of duck-typed “Magic Methods”. Unusually (for C#), these methods are special because of their name, not because of the interface they’re on!
.GetAwaiter
GetAwaiter()
lets you define what happens when a value is awaited.
class Program
{
static async Task Main(string[] args)
{
await 10000; // Delays execution by 10,000ms
}
}
public static class IntExtensions
{
public static TaskAwaiter GetAwaiter(this int i)
{
return Task.Delay(i).GetAwaiter();
}
}
.Add
.Add<T>
lets you define how to include a value in a collection when using the collection initializer syntax.
In this example, we’ll teach C# to let you include one list inside another, by flattening the inner list:
class Program
{
static void Main(string[] args)
{
var list1 = new List<string> {"two", "three", "four"};
var list2 = new List<string> {"one", list1, "five"};
// list2 is "one, two, three, four, five"
}
}
public static class ListExtensions
{
// Tell C# that we know how to include an IEnumerable in a list
public static void Add<T>(this List<T> list, IEnumerable<T> things)
{
foreach (var thing in things)
{
list.Add(thing);
}
}
}
C# Garbage Collector implementation Curiosity
The C# garbage collector is implemented as a single 1.8 MB, 52,000 line C++ file.
https://raw.githubusercontent.com/dotnet/runtime/main/src/coreclr/gc/gc.cpp