user1137486
user1137486

Reputation: 41

get a reference of object from List of objects in c#

i want to get a reference from a list of objects on an object ,

so the reference i want object type

i will explain in the following example

i have a method like

method (ref Foo foo)
{
//
}

and i have a list of Foo

List<Foo> listFoo;

and i want to call this

method(ref listFoo[i])

so this return a reference of a listfoo and i want the reference of the foo number i in the list

thanks

Upvotes: 0

Views: 4217

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062975

If you mean the direct array reference; you cannot obtain that via a list. Not least, this is because the list is free to reassign the underlying array at any point - rendering your reference confusing at best.

If it was an array, the you could use the method(ref arr[index]) approach you mention; but only with arrays.

Note: this trick is only useful in two scenarios:

  • you want to reassign the value in the array
  • you want to access a struct in-situ, without causing it to be copied

For most purposes, passing the object reference is fine, i.e.

Method(Foo foo); // Foo is a class
...
Method(list[i]); // pass the reference to the object, unrelated to the container

Upvotes: 1

Related Questions