3

So when I create an object, I use something like:

Object objectName = new Object();

And I get an object which I can refer to as objectName when calling methods like

objectName.method(parameter);

But how do I make it so I can create an object that I can refer to using a name from a string, something like:

string objectName = "myName";
Object [objectName] = new Object();

And then refer to it like:

myName.method(parameter);

So somehow insert the string objectName into the actual name of the new object. How would I do this?

EDIT: I stumbled across this question in my own profile 5 years (and a CS degree) later, and laughed. The use-case for this was creating objects to store data about locations in a video game world, and I didn't at the time realize that you could have objects without names. The solution I actually would have needed would simply have been an array of objects.

vasilescur
  • 240
  • 2
  • 5
  • 16
  • 2
    Why do you need to do this? What are you trying to accomplish? – yoozer8 Feb 07 '14 at 14:24
  • [Same Question](http://stackoverflow.com/questions/11888144/name-variable-using-string-net) – Jonesopolis Feb 07 '14 at 14:24
  • @48klocs different questions. That asks about the class being specified by the string, whereas this one is about naming the variable based on a string – yoozer8 Feb 07 '14 at 14:25
  • 3
    I am not sure why you would want to do this. Please explain why you wish to do this and you will more than likely get a better solution to your problem. – mbx-mbx Feb 07 '14 at 14:27
  • I didn't realize you were moving beyond reflection and into dynamic codegen or something. Not only will that not work in C# (maybe you can cobble something together in T4), I can think of no language where this (changing variable names at runtime or something) even approaches a seemly idea. – 48klocs Feb 07 '14 at 14:29
  • Sorry about the confusion; what I am trying to do is quickly populate a large array with some sort of "object factory", and then refer back to individual objects by referring to their name. The object names will be generated according to some data that I will store in them. This is part of a world storage/loading algorighm for a game that I am making. If possible, I would like to also specify the class from which the object is to be created with a different string. Thank you all for your answers. – vasilescur Feb 07 '14 at 15:42

3 Answers3

7

What you're trying to do almost certainly points to a problem with your design.

It isn't possible in C# to do something like this. The closest you'll get is using a dictionary:

var objectDictionary = new Dictionary<string, object>();

objectDictionary.Add("myName", new YourClass());

// .. then
var objInstance = objectDictionary["myName"] as YourClass;
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • It is possible to do this in C# (see my answer). And if I did go the dictionary route, I wouldn't do it like this, because it returns the same object instance all the time. Instead, I'd store a delegate (`Func`) that called the type's constructor. – Joel Coehoorn Feb 07 '14 at 14:35
  • @JoelCoehoorn Honestly I'm not sure how our answers relate (maybe I just haven't woken up properly yet). It appears that our answers are answering two different questions. Clearly mine is incorrect. – Simon Whitehead Feb 07 '14 at 22:35
  • I also misread the question. He does indicate through the variable name choice at the end that he wants to access specific object instances, and not create new objects, so this is fine. I tried to remove my downvote, but I can't until you edit. – Joel Coehoorn Feb 07 '14 at 22:44
  • @JoelCoehoorn Appreciate it. I re-read this question, my answer and your answer about 20 times and I was getting quite confused. I just edited it. – Simon Whitehead Feb 07 '14 at 22:53
2

This is almost always a bad idea, but if you must, look into Activator.CreateInstance().

There are two useful (to you) overloads for this method. The first accepts two strings, and will require that you have both the fully-qualified type name and the assembly name where the type you want is defined. The second expects a Type argument, but you can use Type.GetType() method to get the type from a string with the assembly-qualified name for the type.

Since both of those methods require you know something about the assembly, I'll add that you can create some sample code that uses the Type.AssemblyQualifiedName property to tell you what name you need. For example:

string test = "";
string TypeName = test.GetType().AssemblyQualifiedName;
dynamic newString = Activator.CreateInstance(Type.GetType(TypeName));

Note that I used dynamic to declare the final result, because you won't know at compile time what you're working with. This is messy, so again: please just don't go down this road.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

Without further elaboration, it seems like you're trying to create and then reference objects later using the name of the object. If this is the case, you can add a property to the object and then use that to find the object later:

public class myClass
{
    public string name;
    ...
    public myClass(string ObjectName)
    {
        name = ObjectName; //Construct the object with this name you've input
    }
    ...
}

Then, you can store your objects in a collection of some sort:

...
List<myClass> myObjects = new List<myClass>();
myObjects.Add(new myClass("Bob")); //Creating an object we've named "Bob" 
myObjects.Add(new myClass("Alice"));
...

And finally, when you need to find it later:

...
string nameToFind = "Bob";
myClass Bob = myObjects.Find(obj => obj.name == nameToFind); //Find "Bob"
...

Now you can use the Bob object as you'd like, notice this is NOT a solution to your problem the way you stated it. There is no way to make an object's name in code via a string the way you're asking (at least, as far as I know), but you can now reference the object that is named "Bob", what the source code calls it should be irrelevant (ie, you could change Bob to Person or Someone without any real change).

I didn't have time to make sure the code runs as is, but hopefully if my guess of your intentions is right, this will help you figure out what you need to do.

Chartreugz
  • 293
  • 1
  • 10