The World According to Nick
Politics, News, Photography, and Triathlons... What don't I talk about?
Monday, March 01, 2004
<< CodeGuru has a New Look Kerry's Haiti jab >>
Wrapping Up Properties with Delegates
Here's a C# tip that came out of some thoughts I had after reading an article on Code Guru on how to create properties and delegates in managed C++ called Why Don't I Get Those Keywords? What's interesting about the syntax for defining properties is that you are actually creating two functions with this general form:

class MyClass
{
// ... Constructor and Stuff
private:
   type MyProperty;
public:
   __property type get_MyProperty()
   {
      return MyProperty;
   }
   __property void set_MyProperty( type value )
   {
      MyProperty = value;
   }
};


Obviously, type should be replaces with int, string, or whatever the type of the property is... and MyProperty is a generic name for whatever you want to call your property.

One of the nice things you can do in .NET, is create a delegate that is basically a type safe function pointer. But can you create a delegate which is a pointer to a property, instead of a method? At first I thought it would be nice if you could have one delegate that would somehow wrap up both the property get and set in one... but that is not possible. But if you can live with having two delegates for a property, then the syntax for doing that in C++ would be relatively straight forward... following this form:

__delegate type MyPropertyGet();
__delegate void MyPropertySet( type value );

MyClass* obj = new MyClass();

MyPropertyGet* myGet = new MyPropertyGet( obj, &MyClass::get_MyProperty );
MyPropertySet* mySet = new MyPropertySet( obj, &MyClass::set_MyProperty );


The problem is when you try to do this in C#. C# has a completely different syntax for defining properties, that makes the above method impossible. So does that mean that you can't do this in C#... nope. It just means you need to use a little reflection to gain access to the underlying get and set functions that do exist under the hood:


public delegate type MyPropertyGet();
public delegate void MyPropertySet( type s );

MyClass obj = new MyClass();

MyPropertyGet getDel = (MyPropertyGet)Delegate.CreateDelegate( typeof(MyPropertyGet), obj, "get_MyProperty" );
MyPropertySet setDel = (MyPropertySet)Delegate.CreateDelegate( typeof(MyPropertySet), obj, "set_MyProperty" );
# Posted at 11:49 AM by Nick  |  Comment Feed Link No Comments  |  No Trackbacks

 Add to del.icio.us |  Digg this Post | Filed Under: Old Blog

Comments are closed.


© Copyright 2012 Nick Schweitzer
Powered By newtelligence dasBlog 1.9.7067.0
Theme Based on Design By maystar