user2129319
user2129319

Reputation: 1

c# refrencing list

I wanted to know: How to add new members to the list, so that when I change the values of variables will also change the list.

For example:

int a=4;

list<int> l=new list<int>();

l.Add(a);

a=5;

foreach(var v in l)
  Console.WriteLine("a="+v);

Output: a=4

thanks

Upvotes: 0

Views: 66

Answers (4)

Ganesh R.
Ganesh R.

Reputation: 4385

You will have to wrap the int inside a reference type.

Try this:

internal class Program
    {
        private static void Main(string[] args)
        {
            IntWrapper a = 4;

            var list = new List<IntWrapper>();

            list.Add(a);

            a.Value = 5;
            //a = 5; //Dont do this. This will assign a new reference to a. Hence changes will not reflect inside list.

            foreach (var v in list)
                Console.WriteLine("a=" + v);
        }
    }

    public class IntWrapper
    {
        public int Value;

        public IntWrapper()
        {

        }

        public IntWrapper(int value)
        {
            Value = value;
        }

        // User-defined conversion from IntWrapper to int
        public static implicit operator int(IntWrapper d)
        {
            return d.Value;
        }
        //  User-defined conversion from int to IntWrapper
        public static implicit operator IntWrapper(int d)
        {
            return new IntWrapper(d);
        }

        public override string ToString()
        {
            return Value.ToString();
        }
    }

Upvotes: 0

Brian
Brian

Reputation: 7146

You could build out a wrapper container and then just update the wrapper's value as needed. Something like below, for example:

 //item class
 public class Item<T>
    {
      T Value {get;set;}
    }

    //usage example
    private List<String> items = new List<string>();

    public void AddItem( Item<string> item)
    {
        items.Add(item);
    }

    public void SetItem(Item<T> item,string value)
    {
      item.Value=value;
    }

Upvotes: 1

sll
sll

Reputation: 62544

This will not work for a list of value type variables, each time you are changing a value type variable you get a new variable value copy in a stack. So a solution would be using some kind of reference type wrapper.

class NumericWrapper
{
    public int Value { get; set; }
}

var items = new List<NumericWrapper>();
var item = new NumericWrapper { Value = 10 };
items.Add(item);

// should be 11 after this line of code
item.Value++;

Upvotes: 2

Oded
Oded

Reputation: 499212

You need to use reference types if you want that to happen.

With value types, such as int, you get a copy of the variable in the list, not a copy of the reference.

See Value Types and Reference Types on MSDN.

Upvotes: 2

Related Questions