tisdag 22 september 2009

Invoking Properties in .NET

I just stumbled across a problem recently in a Windows Form application I was writing in C#. I wanted to make an update to the GUI from another thread, using Invoke(). The problem was that the update included setting a Property, and not a normal method call. And .NET (at least 2.0, I don't know about fancy 3.5 or upcoming 4.0) don't support Setting and Getting Properties.

This might seem strange, as setting a property is really only making a method call. However, there are two common solutions for this.

The first is to simply write a method that sets the property, and then Invoke() this method. However, I had plenty of classes and places where I had to set Properties, so this was not an ideal solution.

The other solution, which I ended up using, is to use Reflection to get an MethodInfo object of the Property's set. You can then use that object to create a delegate dynamically. In the example, I set the class own SetID property to "4".:


public delegate void test(int i);

public partial class Form1 : Form
{
private int setId = 0;

public int SetID
{
set
{
setId = value;
}
}

void anotherThread()
{
MethodInfo mi = this.GetType().GetProperty("SetID").GetSetMethod();
Delegate del = Delegate.CreateDelegate(typeof(test), this, mi);
this.Invoke(del, 4);
}
}