"Should be a compile time constant" warning when using nameof
See original GitHub issueExample: Log.Information($"Hello {nameof(MyClass)}");
causes a “Message template should be a compile time constant” warning, but nameof
expressions are evaluated at compile time.
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (4 by maintainers)
Top Results From Across the Web
Is nameof() evaluated at compile-time?
Yes. nameof() is evaluated at compile-time. Looking at the latest version of the specs: The nameof expression is a constant.
Read more >[Solved]-Is nameof() evaluated at compile-time?-C#
Yes. nameof() is evaluated at compile-time. Looking at the latest version of the specs: The nameof expression is a constant. In all cases,...
Read more >Message template should be compile time constant-.net-core
Now for the real question: Why is there a warning? The answer is that string interpolation prevents structured logging. When you pass the...
Read more >Class::property.name should be compile-time constant
Hi! I'm trying out Kotlin. Coming from a C# background, I already saw some people suggesting the nameof function. And I also saw...
Read more >Miscellaneous attributes interpreted by the C# compiler
The Obsolete attribute marks a code element as no longer recommended for use. Use of an entity marked obsolete generates a warning or...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Well, after some research, I think that it’s not a mistake. Yes, the
nameof
expression is evaluated at compile-time, but the interpolation is not.The compilation of this code fails
But this code is valid
You may say that this irrelevant in the context of Serilog templates. Because both interpolation and concatenation produce an immutable string, but that’s not completely true either.
Let’s look at IL for the code
On .NET Core 3.1+ it creates a constant
But on old full .NET Framework
string.Format()
is called internallyAnd this is a performance issue https://nblumhardt.com/2014/09/how-not-to-parameterize-serilog-events/
So I’m not sure if we want to treat the interpolation as a constant.
Please let me know what you think.
P.S. There is a proposal for constant interpolated strings. https://github.com/dotnet/csharplang/issues/2951
Well, it works if you target C# 10 C# 10
C# 9