Reputation: 86145
List<A> list = new List<A>();
A a = new A();
A.name = "name1";
list.Add(a);
a = new A();
a.name = "name2";
list.Add(a);
Will the list finally contains the two same A with name equals to "name2"?
How to make use of one variable to achieve this?
Upvotes: 0
Views: 71
Reputation: 630589
You have some syntax errors, it should be:
List<A> list = new List<A>();
A a = new A();
a.name = "name1";
list.Add(a);
a = new A();
a.name = "name2";
list.Add(a);
...but this would result in 2 A elements with different names in the list.
Why? Well the a
variable points to a new A
instance, that reference gets added to the list, then a
points to a new reference with the new A
you create the second time, then that reference gets added to the list...so the list ends up with 2 distinct object references in the end - to different A
instances each with their own name
.
Upvotes: 1
Reputation: 935
Have you tried using Hashset(of T)? You made need to create an IComparer for your class but it should only add one when two objects are equal.
Upvotes: 0
Reputation: 300728
The list will contain two different instances of Type A; one with a name set to "name1", the other set to "name2".
Upvotes: 4