C# Tip 💡 – Did you know we can get info about the caller of a method using C# (5+) info attributes?
The example below shows the caller member name, file path and line number being outputted as we have annotated the parameters of the TraceMessage method with the CallerMemberName, CallerFilePath and CallerLineNumber attributes.
These are really useful and can help with logging and debugging as we don’t have to try and visually 👀 parse a long stack trace to pinpoint where something might have went wrong …
There is no performance overhead as the compiler simply replaces the parameters with constant strings, so it is no different from passing your own constant string at runtime. Here’s some example IL which shows this point …
What do you think?
Have you used info attributes before?
More information from Microsoft ->
Attributes interpreted by the C# compiler: Tracking caller information | Microsoft Learn