Strah Behry
Strah Behry

Reputation: 581

Can I make the name of a new object variable in c#?

For example:

car Audi = new car();

Is it possible to something like this:

string name = Microsoft.VisualBasic.Interaction.InputBox("Name of new car?", "Add car");
car name = new car();

Sorry if this is a stupid or duplicate question.

Upvotes: 2

Views: 73

Answers (4)

rassa45
rassa45

Reputation: 3550

The only way I can think of doing it is a C# version of

car = Car() //basically Python way of initializing car

del car

car = Thing()

Upvotes: -2

Luke
Luke

Reputation: 5076

This isn't possible as variable names are converted to addresses in memory whenever you compile the program.

Since you're trying to name the variable after you compiled the program during runtime, it wouldn't make a difference since it's no longer a human readable name.

Upvotes: 1

xanatos
xanatos

Reputation: 111820

No, you can't. In C# variables must be known at compile time, together with their names...

What you can do is have a collection where to put all your cars... Like:

var allmycars = new Dictionary<string, Car>();

string name = Microsoft.VisualBasic.Interaction.InputBox("Name of new car?", "Add car");

car mycar = new car();
allmycars.Add(name, mycar);

then you can:

foreach (KeyValuePair<string, car> onecar in allmycars)
{
    string name2 = onecar.Key;
    car car2 = onecar.Value;

    Console.WriteLine(name2);
}

Upvotes: 2

Habib
Habib

Reputation: 223187

No you cannot do that. But you can use a different data structure for something similar.

Use Dictionary

Dictionary<string, car> dictionary = new Dictionary<string,car>();
if(!dictionary.ContainsKey(name))
{
     dictionary.Add(name, new car());
}

Upvotes: 2

Related Questions