Jeff Key

It works on my machine

Sponsors

My Job

My stuff

Old stuff

Useful Stuff

Reflecting on properties and fields (literally and figuratively)

The honorable Mr. Fowler today posted that he's +1 for .NET properties and -1 for reflection's differentiation between the two.  His complain is that while you can access both on an object with the same syntax you cannot access them with the same code via reflection.

This is true, but getting around it is simple enough, even if you've already written reflection code to handle fields.  The answer: refactor it!  Extract your getter/setter code to their own methods and create an additional overload that handles properties.  You can get all fields and properties via GetMembers by using the GetFields and GetProperties BindingFlags in addition to whatever criteria you have.  While iterating through these members, simply pass your MemberInfo to one of the overloaded methods and you're set.

Comments

Grant said:


I would have preferred that C# use a hybrid approach to properties, indexers, operators, etc. You'd define members with a specific syntax (e.g. setName, getName, opAdd, opIndex, etc.). These members would be mapped to the appropriate syntax in the language.

For example:

A.Name=B.Name;

would be mapped to:

A.setName(B.getName());

so you get the benefit of the terse syntax.

But you also get the advantage of a consistent image of the reflected class because all these special operations are exposed via ordinary methods.

You get the benefit of being able to call these functions naturally from languages that do not support the terse version of the syntax. And you get the terse syntax for classes written in languages that don't natively support the terse syntax.

Note that this would have alleviated the need to add the "new feature" of differing access levels for getters and setters in C# 2.0. It would potentially allow for virtual operators. It would remove the need for special operator or property declaration syntax.

Anyway, just thinking out loud...
# February 5, 2004 9:25 AM