Lojol
Lojol

Reputation: 653

List<T> - do I pass objects or references?

Well I have looked into generics and have following question:

List<someClass> list=new List<someClass>

SomeClass MyInstance=SomeClass();

list.Add(MyInstance);

I am not sure what will be added to list - reference or object of reference type (pointing to actual value of MyInstance).
EDIT: Or I will add value (that is reference data type) which points to actual object?

Thanks

Upvotes: 15

Views: 13692

Answers (6)

holmes2136
holmes2136

Reputation: 487

If you dispose your object like the following

MyInstance = null

then, you can't read the MyInstance object ,

but you still can read the object in the list,

because you have two references point to the MyInstance ,

In other words,the object has two reference ,

one is

SomeClass MyInstance=SomeClass();

the other one is be stored in the list,

and you just dispose one of them,

so you still can read the list[0]

Upvotes: -1

holmes2136
holmes2136

Reputation: 487

The list will store the reference of the object instead of the object instance.

Actually,the List store value by use array,and array store the reference on the stack and store the object instance on the heap.

Upvotes: -1

Conrad Frix
Conrad Frix

Reputation: 52675

Assuming someClass is a reference type (e.g. class) and not a value type (e.g. struct) then its a reference.

Also I admit it would be pretty devilish to define a struct with the name someClass

struct someClass

And here's the obligatory link to the Jon Skeet article on parameter passing.

Upvotes: 6

explorer
explorer

Reputation: 12110

a reference will be added since MyInstance is of reference type

Upvotes: 1

Lee
Lee

Reputation: 144206

Since someClass is a reference type, a reference to MyInstance will be copied into the list.

Upvotes: 4

Ed Swangren
Ed Swangren

Reputation: 124790

When you deal with reference types you are always dealing with references, so a reference will be added to the list (a copy of the reference actually). You don't actually have a choice; that's how the language works.

Upvotes: 20

Related Questions