C#: how to get an object by the name stored in String?

19,857

Solution 1

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.

Solution 2

No, not all objects have a Name property (for starters).

But you can store objects of interest in a Dictionary<string, object>. You could also get a Control by name, the exact method would depend on the UI library.

Share:
19,857
disserman
Author by

disserman

Updated on June 28, 2022

Comments

  • disserman
    disserman almost 2 years

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

    i.e. get this.obj0 using

    string objectName = "obj0";
    executeSomeFunctionOnObject(this.someLoadObjectByName(objectName));
    
    • Sander Rijken
      Sander Rijken over 14 years
      Can you give an example of how this name should map to the object? Are you looking for an object instance, or a type? Do you want existing instances, or create new ones?
  • Keith Loughnane
    Keith Loughnane almost 10 years
    It's rare that someone clearly says no it can't be done so you can move on and look at a different approach. Thanks.