Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is List<T> a pointer?

Tags:

c#

list

pointers

I noticed that the behavior of List<T> is different from an other simple object, say String for example. The question can seem newbie but that really struck me cause I thought that List<T> were simple objects.

Take for instance the following code:

List<String> ls1 = new List<String>();
ls1.Add("a");
List<String> ls2 = ls1;
ls1.Add("b");

At the end, ls1 will be equal to {"a", "b"} and so will ls2. This is really different from the behavior of this code:

String s1 = "a";
String s2 = s1;
s1 = "b";

Where s1 is at the end equal to b and s2 equal to a.

That means that List<T> is in fact a pointer right?

like image 435
Otiel Avatar asked Oct 18 '11 13:10

Otiel


People also ask

Is a list a pointer?

List<T> is an object, so yes, it is "like a pointer" (I use that term loosely since objects in managed code are not called "pointers", they're called references). List and String are identical in this regard.

What type is a list in C#?

C# - List<T> The List<T> is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that comes under System.Collections.Generic namespace.

What is a list in asp net?

A list is a collection of items that can be accessed by index and provides functionality to search, sort and manipulate list items.

Can you have a list in a list C#?

List, nested. A List can have elements of List type. This is a jagged list, similar in syntax to a jagged array. Lists are not by default multidimensional in C#.


2 Answers

List<T> a reference type, so yes it behaves like a pointer.

String is also a reference type, but strings are immutable and they behave like value types (contrast with reference types) in some cases hence your confusion here.

There is a good explanation of why string work this way here: In C#, why is String a reference type that behaves like a value type?

like image 61
Mike Mooney Avatar answered Nov 15 '22 16:11

Mike Mooney


The line s1 = "b" actually assigns a new reference to s1. s1 and s2 now refer to two different objects.

The changes to the List<string> object referred to by ls1 are visible through all references to that object, including ls2. When you make ls2 = ls1 you are basically saying that both ls1 and ls2 refer to the same object. Changes to the object via the reference variable ls1 are visible via the reference variable ls2.

like image 28
Michael Goldshteyn Avatar answered Nov 15 '22 18:11

Michael Goldshteyn