Reputation: 63
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!
Upvotes: 2
Views: 1921
Reputation: 81675
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...
Upvotes: 7
Reputation: 1503429
It's important to understand that you're naming variables there, not instances. Objects don't generally have names. Next, if you want a collection, just say so:
List<Word> words = new List<Word>();
words.Add(new Word(link, 24));
...
(Or you can use an array, or whatever's most appropriate for your use case.)
Variables are never declared dynamically with dynamic names in C# - your code specifies the exact name.
If this doesn't help you, please tell us more about what you're trying to achieve, rather than how you expected to be able to achieve it.
Upvotes: 3
Reputation: 3417
You can't do anything like that in a compiled language like c#. The best you can do is to create an array of Words.
Word[] words = new Word[10];
words[0] = new Word(link, 24);
...
On another note, have you considered better names than word1, word2, etc., that would explain what the purpose of the variable is?
Upvotes: 2