Introduction
Here is a function which you can use to get the instance of a member object given just a string name.
Background
So, why in the world would you want to get an instance of something if you're already in that class? Don't you know what's in there already?
In my case, I had a base class which was loading a configuration file and needed to find an object in the derived class. The config file contained only the name,
and I happened to know the type of the object. What I needed was a way to convert that object's string name into a reference to the instance.
It works great if the object you're searching for is a class. To search for properties or other possible members of the parent class, you would
need further customize it beyond what I show here.
Using the code
You can find the field you want through a function as shown below, which makes a nice shortcut so you don't have to put reflection code all through your app.
If you want to find a field of type MyCustomType
with an instance name of
_myInstance
, you would call it like this:
MyCustomType foundIt = FindField<MyCustomType>("_myInstance");
using System.Reflection;
public T FindField<T>(string name) where T: class
{
FieldInfo field = this.GetType().GetField(name,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
return field.GetValue(this) as T;
}
Points of Interest
In order to cast the return value to type T
, you need to have "where T: class
" in the function declaration. This is what limits this particular example to objects
which happen to be classes.
This isn't terribly interesting or complex until you consider what I was trying to do. In my case, I used it to hook a
ValueChanged
callback
in one object to a PropertyChanged
event in another object so I could automatically transfer a piece of data to the second object when the value changed in the first one.
It's a way to wire black box classes to each other without having to recompile. My configuration file determined what two objects I wanted to hook together,
and no code which actually needed to know that the two objects were trading information.
My classes had the advantage of enforced data hiding which gives great loose coupling.
Their entire interface was through named access points, and they were hooked up via an external configuration file so the classes didn't even need to know where their data was going.
It can be taken to even more of an extreme where you could hook up two MEF-based plug-ins that don't even know each other's types via a reference.