Today I ran into an issue that I had not encountered in C#, which is getting unusual for me as I have been writing .Net apps in C# since 2001. When initializing a private instance variable, .Net does not allow a reference to “this”. Some nugget of knowledge on this subject is floating around in the back of my head, but did not float to the front until I got an error in the VS IDE today. Here is an example:
public class Blah : BlahBase
{
private MyType t = new MyType(this); //Doesn’t work!
}
In this example, I wanted the instance of MyType to hold a reference to its parent object. I won’t go into all of the reasons here, but this pattern makes it possible to simplify a lot of things in my Blah class. Additionally, I need to be able to instantiate a lot of objects of type MyType, and also do it in any class types that inherit from BlahBase. My descendant classes will have a number of constructors, so doing initialization in all of these constructors of the MyType instance fields will become cumbersome and I could very easily introduce bugs with one missing line here or there.
To give a reference to Blah (or any given descendant class of BlahBase) to an instance of MyType at declaration, I decided to turn to reflection. In the BlahBase constructor, I looped through all the the Non-pubic, Instance fields of the current type using this.GetType(). I then check the type of each field to see if it is a MyType, and call FieldInfo.GetValue() to get a reference to the object, and Invoke() to set the reference to “this” via reflection as well. While the reference is not actually given to the MyType instance at initialization, it is given to each MyType instance before anything in in a child class of BlahBase can use it.
I keep telling myself that this is bad. Calling things via reflection is not very type-safe. Errors tend to happen at runtime instead of compile time. Additionally, reflection is slower than direct method calls or assignments. But really, I am probably dealing with 20 instances of MyType as a worst case. The performance difference is not going to be very bad. I will tend to write cleaner, more bug free code using this structure, as will other developers using BlahBase as a base type.
However, this is not type safe. The wrong change to MyType could cause a run-time error in the future. However, this is an error that will be very easily detected in testing. I am willing to trade for the over-all better OOP design here, and more developer productivity.
