Click here to Skip to main content
15,891,902 members
Articles / Programming Languages / C#
Tip/Trick

Get an object instance given just a name

Rate me:
Please Sign up or sign in to vote.
2.50/5 (2 votes)
15 Oct 2013CPOL2 min read 8.5K   3   1
How to get a reference to a class member when all you have is its name and type.

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: 

C#
MyCustomType foundIt = FindField<MyCustomType>("_myInstance"); 
C#
using System.Reflection;
/// <summary>
/// Look up and return a field instance (an object declared within a class)
/// from "this". This is handy if you're using a base class type and are 
/// looking to see if a derived class has a particular named object of 
/// known type declared as a member. It is also very handy if you have a 
/// text name from a config file, and need to find the instance of that
/// object.
/// </summary>
/// <typeparam name="T">Type of the object to be searched for.</typeparam>
/// <param name="name">Name of the instance of the object to be found</param>
/// <returns>Reference to the field, or null if not found.</returns>
public T FindField<T>(string name) where T: class
{
	// If this class has the specified input, then return it.
	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. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
jfriedman15-Oct-13 19:51
jfriedman15-Oct-13 19:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.