Monday, September 24, 2012

Caller Info Attributes in C# 5.0

Caller Info Attributes is a new feature in C# 5.0, Caller Info Attributes instructs the compiler to obtain and feed information into the parameter’s default value. You can tag optional parameters using Caller Info Attributes.
Three Caller Info Attributes are
  • [CallerMemberName]  – It applies the caller’s member name
  • [CallerFilePath] -  It applies the path to the caller’s source code file
  • [CallerLineNumber]-  It applies the line number in the caller’s source code file
The below piece of code demonstrates all three attributes
   1: using System;

   2: using System.Runtime.CompilerServices;

   3: class Program

   4: {

   5: static void Main()

   6: {

   7:   Demo();

   8: }

   9: static void Demo (

  10: [CallerMemberName] string memberName = null,

  11: [CallerFilePath] string filePath = null,

  12: [CallerLineNumber] int lineNumber = 0)

  13: {

  14:    Console.WriteLine (memberName);

  15:    Console.WriteLine (filePath);

  16:    Console.WriteLine (lineNumber);

  17: }

  18: }
The output of the code as below
C:\Projects\Program.cs (Assuming your project is located in this path)
Caller Info attributes are useful for writing logging functions and for implementing change notification patterns. The following method can be called from property’s set accessor
   1: void RaisePropertyChanged( [CallMemberName] string propertyName = null)

   2: {


   4: }
More can be read here
Post a Comment

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts