Why only literal strings saved in the intern pool by default?

The short answer: interning literal strings is cheap at runtime and saves memory. Interning non-literal strings is expensive at runtime and therefore saves a tiny amount of memory in exchange for making the common cases much slower. The cost of the interning-strings-at-runtime “optimization” does not pay for the benefit, and is therefore not actually an … Read more

In a switch vs dictionary for a value of Func, which is faster and why?

The short answer is that the switch statement executes linearly, while the dictionary executes logarithmically. At the IL level, a small switch statement is usually implemented as a series of if-elseif statements comparing equality of the switched variable and each case. So, this statement will execute in a time linearly proportional to the number of … Read more

Why does struct alignment depend on whether a field type is primitive or user-defined?

I think this is a bug. You are seeing the side-effect of automatic layout, it likes to align non-trivial fields to an address that’s a multiple of 8 bytes in 64-bit mode. It occurs even when you explicitly apply the [StructLayout(LayoutKind.Sequential)] attribute. That is not supposed to happen. You can see it by making the … Read more

Asynchronous iterator Task

A more “batteries-included” implementation of this kind of thing, including language support, is now available as of C# 8.0. Now, when using at least C# 8.0 (or higher) with .NET Standard 2.1 (or higher) and/or .NET Core 3.0 (or higher), the code from the original question may be written as follows: private async IAsyncEnumerable<char> TestAsync(string … Read more

Is casting the same thing as converting?

Absolutely not! Convert tries to get you an Int32 via “any means possible”. Cast does nothing of the sort. With cast you are telling the compiler to treat the object as Int, without conversion. You should always use cast when you know (by design) that the object is an Int32 or another class that has … Read more