Wednesday, November 21, 2012

Using Caller Info Attributes in .NET 4.5

Introduction

When developing complex .NET applications sometimes you need to find out the details about the caller of a method. .NET Framework 4.5 introduces what is known as Caller Info Attributes, a set of attributes that give you the details about a method caller. Caller info attributes can come in handy for tracing, debugging and diagnostic tools or utilities. This article examines what Caller Info Attributes are and how to use them in a .NET application.  

Overview of Caller Info Attributes

Caller Info Attributes are attributes provided by the .NET Framework (System.Runtime.CompilerServices) that give details about the caller of a method. The caller info attributes are applied to a method with the help of optional parameters. These parameters don't take part in the method signature, as far as calling the method is concerned. They simply pass caller information to the code contained inside the method. Caller info attributes are available to C# as well as Visual Basic and are listed below:

Caller Info Attribute Description
CallerMemberName This attribute gives you the name of the caller as a string. For methods, the respective method names are returned whereas for constructors and finalizers strings ".ctor" and "Finalizer" are returned.
CallerFilePath This attribute gives you the path and file name of the source file that contains the caller.
CallerLineNumber This attribute gives you the line number in the source file at which the method is called.
A common use of these attributes will involve logging the information returned by these attributes to some log file or trace.

Using Caller Info Attributes

Now that you know what Caller Info Attributes are, let's create a simple application that shows how they can be used. Consider the Windows Forms application shown below:

Read more: Codeguru

Posted via email from Jasper-Net