user496949
user496949

Reputation: 86145

Is the following correct?

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

Answers (3)

Nick Craver
Nick Craver

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

CertifiedCrazy
CertifiedCrazy

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.

MSDN Hashset

Upvotes: 0

Mitch Wheat
Mitch Wheat

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

Related Questions