paperduck
paperduck

Reputation: 1195

In C#, How can I know when the assignment operator (=) will copy the value or memory address (reference)?

For example, after this code runs, what does list2 contain, and how can I be confident in that?

List<SomeClass> list1 = new List<SomeClass>();
List<SomeClass> list2 = new List<SomeClass>();

SomeClass sc = new SomeClass(); // assume assignment operator (=) 
                                // is defined for this class

list1.Add(sc);
list2.Add(new SomeClass());
list2[0] = list1[0];
list1.RemoveAt(0);

Upvotes: 1

Views: 1217

Answers (3)

Patrick Hofman
Patrick Hofman

Reputation: 157098

The = operator applied to value types will copy the one value to the variable. On all other (reference types) it will 'copy' the memory address.

The full list of value types (source MSDN):

  • bool
  • byte
  • char
  • decimal
  • double
  • enum
  • float
  • int
  • long
  • sbyte
  • short
  • struct
  • uint
  • ulong
  • ushort

About the = operator (according to MSDN):

The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result. The operands must be of the same type (or the right-hand operand must be implicitly convertible to the type of the left-hand operand).

Upvotes: 3

Vladimir Potapov
Vladimir Potapov

Reputation: 2437

If i get this right there class and struct,sow tow classes will are depended that mean if you have

List<SomeClass> list1 = new List<SomeClass>();
List<SomeClass> list2 = new List<SomeClass>();

if you make change list1,the list2 is gonna change to,list2 point the same class.

But if you use struck it will not chage because they undepended and do not poin to the same place.

Upvotes: 0

Drew Noakes
Drew Noakes

Reputation: 311285

The = operator copies struct types by value, and class types by reference.

C# does not allow overriding the = operator, as may be done in C++.

Assuming your are coming from a C++ perspective, consider that in C++ the value/reference semantics of memory is determined by the user of a type, whereas in C# it is the designer of the type that decides.

So assuming SomeClass is a class as the name suggests, when your example code completes, list2 will contain sc and the anonymous instance created for list2 is unreachable and will be garbage collected.

Also the syntax of list1.RemoveAt[0] is incorrect. You must use () instead of [].

Upvotes: 4

Related Questions