New Feature of Visual Studio 2012 - Getting Caller Information

Introduction

In today's article you will learn about one of the new features of Visual Studio 2012, getting caller information in C#.

C# 4.5 has an easier way to obtain information about the caller of a method. By using the Caller Information Attribute we can get the File Path of the source code file, Line number in the source code, and the Member Name of the caller. This Information can be used for various purposes such as Tracing, Debugging and Creating Diagnostic Tools. To obtain this information we will use the attributes applied to optional parameters, each of which has a default value.

Step 1

First of all start a new project in Visual Studio 2012.

tracing2.jpg

You can choose New Project, either Console Application or Windows Application. Here I chose Console Application.

tracing1.jpg

Step 2

Now in the code, add an assembly, as in:

using System.Runtime.CompilerServices;

After adding this assembly we will move to the code. Use the following code:

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            DoProcessing();

        }

        public static void DoProcessing()

        {

            TraceMessage("Something happened.");

        }

 

        public static void TraceMessage(string message,

                [CallerMemberName] string memberName = "",

                [CallerFilePath] string sourceFilePath = "",

                [CallerLineNumber] int sourceLineNumber = 0)

        {

            Console.WriteLine("message: " + message);         

            Console.WriteLine("member name: " + memberName);

            Console.WriteLine("source file path: " + sourceFilePath);

            Console.WriteLine("source line number: " + sourceLineNumber);

            Console.ReadKey();

           

        }

    }

}

Step 3

Now we will debug this application to get the output.

tracing3.jpg

As you can see in the output it's showing the Member Name, Message, File Path and Line Number of the Application.

If you are working on a Windows application then you simply need to replace the Console.WriteLine with the MessageBox.Show and you will get the same output.


Similar Articles