views:

135

answers:

3

Good day,

is it possible in C# to get an object by name?

i.e. get this.obj0 using

string objectName = "obj0";
executeSomeFunctionOnObject(this.someLoadObjectByName(objectName));
+6  A: 

No, it's not.

Objects don't have names - variables do. An object may be referenced by any number of variables: zero, one or many.

What you can do, however, is get fields (static or instance variables) by name (using Type.GetField) and get the values of those fields (for a specific instance, if you're using instance variables).

Depending on what you're trying to do, you might also want to consider a dictionary from names to objects.

Jon Skeet
A: 

You can't access an object by name. Using reflection, though, you can all fields and properties of a class (by name, if you want). If your object is stored in a field level variable or in a property, then this will give you what you want:

Type myType = typeof(MyClass);
FieldInfo[] myFields = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

PropertyInfo[] myproperties = myType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

You can also call GetField and GetProperty (singular) and pass in a string to have it return a single member matching that name (make sure to check for null).

Read these pages for more information on reflection methods of use in this situation:

GetProperty

GetProperties

GetField

GetField

Gabriel McAdams
A: 

Well I think what you are looking for is Reflection.

You can see a good example here: http://www.switchonthecode.com/tutorials/csharp-tutorial-using-reflection-to-get-object-information

As said before - objects don't have names but you can traverse the objects and get their type and act accordingly.

This blog here shows a real good example of traversing and usage of reflection.

This should be a good start for sure. Enjoy!

yn2
You can't traverse 'all objects'.
Henk Holterman
@Hank, why not? see my edition.
yn2
yN2, the OQ wants to search all 'loaded' objects (I think). That is closer to the Garbage Collection than to Reflection.
Henk Holterman