Compiler directive for current method name #3389
Replies: 7 comments
-
The example you give is certainly cumbersome, but there's a simpler way to achieve this today, with a very simple helper method:
The compiler will ensure the right name is passed, and the JIT will likely inline it, giving minimal overhead.
They weren't forgotten - they were such a fertile source of subtle and hard to diagnose issues that the folks behind C# 1.0 deliberately decided not to include a preprocessor. It wasn't forgotten, it was excluded. Edited to remove code debris. |
Beta Was this translation helpful? Give feedback.
-
Plus, consider how to get a method name from a property setter or getter (no CallerMembeName can be passed there). |
Beta Was this translation helpful? Give feedback.
-
This is a (weaker) duplicate of #345 I would much prefer that instead of this. |
Beta Was this translation helpful? Give feedback.
-
@nmarcel Can you please expand on what you're saying here? The Instead of this:
|
Beta Was this translation helpful? Give feedback.
-
@theunrepentantgeek what I mean is that you cannot know (easily, without reflection):
|
Beta Was this translation helpful? Give feedback.
-
@nmarcel |
Beta Was this translation helpful? Give feedback.
-
Actually compiler/pre-processor directives are so useful that they weren't excluded from C# rather they were diminished. https://www.programiz.com/csharp-programming/preprocessor-directives Macro directives were incredibly important to things like ATL. and MFC. Having been a developer since 1975 I can attest to their importance :-) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
From @genifycom on Thursday, April 23, 2020 6:11:15 PM
Issue Title
Could we please have a compiler directive for the current method?
General
Questions about how to print out the current method name date back to the beginning of dotnet core. These "solutions" usually require reflection or CompilerServices like CallerMemberName
e.g.
string method = $"{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName}.{System.Reflection.MethodBase.GetCurrentMethod().Name}";
These options are long, cumbersome and for async method often get changed by the underlying implementation (e.g. MoveNext or OnResume). Also if the compiler decides to inline or optimize, these methods may interfere with that.
Is it possible to have a compiler directive like #Method that gets replaced at compile time with a string containing the currently compiling method?
So then we can write out the method entry e.g.
Serilog.Log.Logger.Information("Starting #Method");
Compiler directives were such a huge and useful part of C++ that seem to have been forgotten in C#.
Copied from original issue: dotnet/core#4608
Beta Was this translation helpful? Give feedback.
All reactions