Mar 6, 2013

New types from .NET 4.5

Hi.

While experimenting with WPF programing I've just stumbled on a nice, new class in .Net 4.5 (thanks to Resharper) named CallerMemberNameAttribute.

The first thing you can figure out based on its name is that it is an attribute. It's only applicable to parameters and is meant to make developers live easier when it comes to find out the name of the caller method / property / event / etc :)

Basically you add this attribute to any parameter of type string with a default value and the compiler will do its magic.

Bellow you can see an example:

public partial class Form1 : Form
{
	public Form1()
	{
		InitializeComponent();
		
		button2.Click += delegate
		{
			Foo();
		};
	}

	private void Foo([CallerMemberName] string caller = null)
	{
		MessageBox.Show("Called from : " + caller);
	}
}

This is really useful for implementing INotifyPropertyChanged interface.

Note that this gives you only the name of the member calling the method, not the type in which this method is defined.

As any other feature developers should not abuse it. For instance, IMHO, using this feature with indexers should be avoided:

public partial class Form1 : Form
{
	public Form1()
	{
		InitializeComponent();
		
		button2.Click += delegate
		{
			MessageBox.Show( this[0] );
			MessageBox.Show( this[1] );
		};
	}

	private string this[int n, [CallerMemberName] string caller = null]
	{
		return n > 0 ? this[n-1] : caller + "(" + n + ")";
	}
}

For more information, look into the documentation.

Happy codding!

No comments: