Caller Info Attributes in CSharp

Dheeraj Kumar Gunti

Reading Time : ( words)

There are lot of cool features in C#. We will discuss one of them in this article. Caller Info Attributes are one of the nice features which are used to pass caller information implicitly to a method.

This feature helps in logging the complete information about the caller to any specific method. In this article we will try to use caller info attributes in Logging details when any error occurs.

There are three important attributes in this aspect.

  • CallerMemberName
  • CallerFilePath
  • CallerLineNumber

CallerMember - It Allows you to obtain the method or property name of the caller to a method.

CallerFilePath - It Allows you yo obtain the full path of the source file that contains the caller. Thihs is basically a file path at the time of compile.

CallerLineNumber - Allows you to obtain the line number in the source file at which the method is called.

(Courtesy - VS Docs)

Lets see a simple example.

I am creating a small helper call which takes exeption object as one parameter and the other parameters are caller info attributes.

We are using this helper class in one of the method where we are trying to creating an error to see the output of the helper method.

We surrounded the piece of code in try catch block to catch the exception. Run the application and lets see the output.

This is a simple way of getting the complete information about the caller and can be easily logged to identify the exact place where we got the error.

Thanks and Enjoy Coding....