Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an object with name from string? [duplicate]

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.

like image 898
vasilescur Avatar asked Jan 11 '23 06:01

vasilescur


2 Answers

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;
like image 146
Simon Whitehead Avatar answered Jan 20 '23 20:01

Simon Whitehead


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.

like image 20
Joel Coehoorn Avatar answered Jan 20 '23 18:01

Joel Coehoorn