Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to store references to objects in list?

Tags:

c#

I would like to be able to assign values to list objects without directly referencing them:

Pseudo example:

List<int> intList = new List<int> { 0 };
???? intPointer = ref intlist[0];

*intPointer = 1;  // I know * isn't possible here, but it is what I'd like to do

Console.WriteLine(intList[0]);

and it would output 1.

I'm thinking that this isn't possible, but I just wanted to make sure I wasn't missing anything.

Also, I'm not looking for an example that uses unsafe, I'm curious if this is possible in managed code.

like image 635
afuzzyllama Avatar asked Nov 14 '12 00:11

afuzzyllama


1 Answers

C# doesn't have a concept of "ref locals" (the CLR does though). So you'll need to wrap the values in a reference type that you can mutate. For example,

public class Ref<T> where T : struct
{
    public T Value {get; set;}
}

List<Ref<int>> intRefList = new List<Ref<int>>();
var myIntRef = new Ref<int> { Value = 1 };
intRefList.Add(myIntRef);

Console.WriteLine(myIntRef.Value);//1

Console.WriteLine(intRefList[0].Value);//1

myIntRef.Value = 2;

Console.WriteLine(intRefList[0].Value);//2

Edit: C# 7.0 added ref locals but they still can't be used in this way because you can't put ref locals into an array or list.

like image 95
Wesley Wiser Avatar answered Sep 20 '22 15:09

Wesley Wiser