Caller Info Attributes in C# 5 Are a Framework-Agnostic Compiler Feature
Join the DZone community and get the full member experience.
Join For Freethe new caller information attributes in c# 5 are excellent news for people tired of writing logging and diagnostic code or implementing inotifypropertychanged. you simply supply the correct attribute for the function parameters with default values and voilà – you get information about the caller for free. consider the following code:
using system; using system.runtime.compilerservices; class program { static void saymyname([callermembername] string functionname = "", [callerfilepath] string filepath = "", [callerlinenumber] int linenumber = 0) { console.writeline("{0}:{1}({2})", filepath, functionname, linenumber); } static void main(string[] args) { saymyname(); } }
the output of this simple program is:
c:\users\toni\documents\visual studio 11\projects\test_console\cstest\program.cs:main(15)
excellent, we have the caller’s information for free. .net 4.5 framework introduced the above used attributes: callermembernameattribute, callerfilepathattribute and callerlinenumberattribute. they are defined in the system.runtime.compilerservices namespace. this means that if you are using visual studio 11 and you are targeting earlier framework, you do not have those types defined in mscorlib.dll. however, even though this might make you think that you are left in the dark, this is a compiler feature which means that these attributes are nothing but a magic keywords for the compiler. they themselves do nothing!
in fact, i have compiled the above program targeting .net 2.0 framework, the earliest target type available in visual studio 11. the trick is to add the right “magic” attributes and it will work since the compiler will interpret them correctly. the full source code is rather short and you can find it as a gist at github .
i based this idea on a similar “hack” for using async in projects targeting .net 4 on the c#5 compiler: https://gist.github.com/1961087 .
Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments