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);
}
}

2 kommentarer:

  1. Back in the day, when I was taught OO it was imperative to use access methods in objects for everything. Even internally, even for public properties (on the otherhand, we were also told never to declare properties as public). Perhaps the paradigm has changed since then, but it is my understanding that C# 3.0 support this methodology.
    However I might be totally wrong on this and as such have only little interest to drill in deeper on the matter. The question obviously has a religious war potential: http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

    SvaraRadera
  2. Intresting thoughts. I find it a bit extreme to never declare public properties. But then again, I've met people who think *all* classes should have interfaces (which I think only adds unnessecary complexity)

    SvaraRadera