Menu

How Glass recovers primary constructor parameters
πŸ“°

How Glass recovers primary constructor parameters

DEV Community: csharpΒ·Zero HeartbeatΒ·2 days ago
#ltzbuipF
#devtocsharp#devto#dev#constructor#field
Long article (1394 words) β€” no AI summary yet.
Reading 0:00
15s threshold

C# 12 lets you write a class header that doubles as its constructor:

public class OrderProcessor ( int retries , ILogger log )

Enter fullscreen mode

Exit fullscreen mode

It reads as if retries and log are fields of the class. They are not β€” not necessarily. By the time the compiler is done, one of them may have become a private field and the other may have vanished entirely, inlined into a property initializer with no trace that it was ever a parameter. Which fate each parameter meets is decided by one rule, and a decompiler has to reverse-engineer that rule from the field table and the constructor's IL. It is a precise piece of pattern matching, and a clean way to watch Glass.NET , the free .NET decompiler, turn a language convention back into source.

The real question

A primary constructor parameter is in scope everywhere in the class body. But the compiler does not keep a parameter around just because it is in scope β€” it keeps it only if some method body actually reads it after the constructor runs.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.