Friday, November 19, 2010

More Native Reflection, Please!

Sometimes you wonder why you keep on producing the same kind bugs again and again...
... and you hope someone will show you how to find a remedy.

This post is left to be found by the programming language designers of today... and whoever finds it interesting.


The Problem - Example #1

PropertyInfo propertyInfo = this.GetType().GetProperty("SomePropertyName");

Above very powerful state of the art reflection fetches a PropertyInfo instance that can be used to set/get property "SomePropertyName". The Type class facilitates a number of reflection services as normal C# members in a very general and loose coupled manner e.g. you enter a string in the GetProperty-method.
The problem comes when someone renames SomePropertyName with a built-in refactoring utility of an IDE. The string argument is a weakness in above code that just waits to break the code.


The Problem - Example #2

[Reference(InitializeFromPropertyId = "EntityId")]
SomeEntity ReferenceEntity
{
get;
set;
}

Imagine that above code is part of an interface or class and it means that the class - when instantiated - will initialize a reference to another entity of type SomeEntity using property EntityId. This time we have the same problem - the string argument in the annotated Reference-attribute won't be changed if the property name is refactored.


Counter Example

Type type = typeof(Org.Foo.Bar.MyClass);

Above works like a charm with refactoring. If MyClass is renamed, the code doesn't break.


The Simple Solution

PropertyInfo propertyInfo = propertyof(Org.Foo.Bar.MyClass.SomePropertyName);

Could you guys* (continue to) make reflection part of the programming language! ... Please ... Soon?

* Anders Hejlsberg and others...