TechBubbles Microsoft Technology BLOG

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.

image

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

Main

C:\Projects\Program.cs (Assuming your project is located in this path)

16

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: {

 3:

 4: }

More can be read here

Share this post :

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

Add Comment

By Kalyan Bandarupalli
TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud