Reputation: 33
I want to dynamically create instances of a class, so I created a dictionary of objects of that class and assign the names by appending a counter to a string. But how do I access the properties of the objects?
The code is something like this:
int count = 0;
string name = "MyInstanceName" + count.ToString();
Dictionary<string, MyClass> d = new Dictionary<string, MyClass>();
d.Add(name, new MyClass(Parameter));
//try to retrieve the Property - this doesn't work
textBox1.Text = d[name.Property];
Upvotes: 3
Views: 1567
Reputation: 6239
You can do this
int count = 0;
string name = "MyInstanceName" + count.ToString();
var d = new Dictionary<string, MyClass>();
d.Add(name, new MyClass());
textBox1.Text = d[name].Property;
You created a Dictionary
that the key is a string
and the value is a instance of MyClass
.
When using Dictionary index, the value between brackets []
should be the key, in this case a string.
myDictionary["keyValue"]
Upvotes: 7
Reputation:
in addition to Alberto Monteiro's answer, don't forget to cast your object:
textBox1.Text = (myClass) d["MyInstanceName1"].Property;
or
var myInstanceX = d["MyInstanceName1"].Property;
textBox1.Text = myInstanceX.myStringProperty();
In C# (unlike VB), you don't need to specify the type of a variable if the compiler can determine it elsewhere, so you can also simplify:
Dictionary<string, MyClass> d = new Dictionary<string, MyClass>();
into
var d = new Dictionary<string, MyClass>();
var is a typed variable declarator (unlike javascript)
Upvotes: 0