Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I name instances in C# automatically?

I'm new here, so please forgive me if this question is stupid. But let me say I couldn't find anything on it.

Whenever you start a new instance, you go:

Word word1 = new Word(link, 24);

But say, how would I name instances automatically? If a method automatically creates new instances, how can it automatically pick a unique name for the instance, for example, word2, word3, word4, etc.

Thank in advance!

like image 815
user1432233 Avatar asked Dec 19 '25 17:12

user1432233


1 Answers

It sounds like you are looking for a "list" of instances. In which case, use a List:

List<Word> words = new List<Word>();
words.Add(new Word(link, 24));

As others have commented, if you need to look up the "variable" by name, a dictionary would work, too:

Dictionary<string, Word> words = new Dictionary<string, Word>();
words.Add("word1", new Word(link, 24));

then you can reference it by that string:

if (words.ContainsKey("word1")) {
  Word useWord = words["word1"];

or reference the class directly:

words["word1"].SomeProperty...
like image 128
LarsTech Avatar answered Dec 21 '25 06:12

LarsTech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!