user3076439
user3076439

Reputation: 11

Passing a value by reference to List.Add()

How could I pass a value by reference to the List?

int x = 2;
List<int> newList = new List<int>();
newList.Add(x);

System.Console.WriteLine(x);
x = 7;
System.Console.WriteLine(newList[0]);
newList[0] = 10;
System.Console.WriteLine(x);

My objective is elements on the list to be related with the previous ones. In C++ I would use a list of pointers, however right now I feel hopeless.

Upvotes: 1

Views: 520

Answers (3)

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

You can't store value types in a .NET generic collection and access them by reference. What you could do is what Simon Whitehead suggested.

I see few solutions of this problem:

1) Create a class which will hold the integer (and possibly other values you might need)

2) Write "unsafe" code. .NET allows usage of pointers if you enable this for your project. This might even require creating custom collection classes.

3) Restructure your algorithm to not require references. E.g. save indexes of values you wish to change.

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can't do it with value types.You need to use a reference type.

(change) You can't do it with object too, you need to define your custom class which has a int property. If you use object it will be automatically perform boxing and unboxing.And actual value never affected.

I mean something like this:

MyInteger x = new MyInteger(2);
List<MyInteger> newList = new List<MyInteger>();
newList.Add(x);

Console.WriteLine(x.Value);
x.Value = 7;
Console.WriteLine(newList[0].Value);
newList[0].Value = 10;
Console.WriteLine(x.Value);

class MyInteger
{
  public MyInteger(int value)
  {
        Value = value;
  }
  public int Value { get; set; }
}

Upvotes: 3

ansible
ansible

Reputation: 3579

ints are primitives, so you are not passing around a pointer,but the value it self.

Pointers are implicit in C#,so you can wrap ints in an object and pass that object around instead and you will be passing a pointer to the object.

Upvotes: 1

Related Questions