共用方式為


.NET 4.5 - Information of Caller Function (Caller Attributes in .NET 4.5)

While debugging code “Who called my function ?” is  a million dollar question. Knowing the origin of your function call is in many cases the first step in debugging any code. Until now a few ways of doing this were to look at the CallStack in visual studio or  a debugger or the most common Exception.StackTrace. .NET 4.5 has added a new feature with which a function can now know who is calling it. The function being invoked can now know the origin of its call … that would include the Function name, File name and the Line number from where the call originated. Developers can now tap this information to provide useful debugging information. These features are part of the System.Runtime.CompilerServices namespace. Here is a sample and its output

image

image

So in MyTestFunction you can now see that the Main function in Program.cs called it from Line 14. The developer can log this as additional information for debugging.

You do this by defining three parameters for your function that will hold your Caller data. You then use the CallerMemberName, CallerFilePath and CallerLineNumber attributes which are part of the System.Runtime.CompilerServices namespace to decorate the arguments of your function.

And in your function these three parameters will now have the Caller function details populated each time the function is invoked.

The way this is implemented is using the Optional parameters feature which was introduced in .NET 4. Take a look at the MSIL for the above code

image

The three parameters that we decorated using the Caller attributes are marked as Optional and in the beginning of the function are loaded with the Caller details.

Which basically means you can also do this.

image

Here instead of leaving those optional parameters to the defaults I am explicitly passing them values. And the output will display the values I passed.

image

Just to show that these are normal optional parameters. And be aware that the developer of the caller function can accidently or intentionally overwrite these values.

This feature need not be limited to just providing debugging information you can also take decisions based on the Caller

image

A very useful feature in .NET 4.5 where your functions can now know details of the Caller function.