Here's a simple integer array.

int[] intArray = new int[5];

Now I make the first element equal to a variable.

a = 10;
intArray[0] = a;

How can I change the variable so the array automatically updates without using referring to the array?


a = 10;
intArray[0] = a;

a = 15; 

// If intArray was referencing 'a' then wouldn't it automatically update?
// Don't want to have to explicitly type "intArray[0] = 15"

Can this be done with arrays or lists?

6 Years
Discussion Span
Last Post by Momerath

If you store objects (reference types) in your List/Array then this behavior will happen automatically. When you store value types (int, bool, float, etc.) then this behavior doesn't happen.

You can convert a value type into a reference type with explicit casting (known as boxing), but changes to the original value type are not reflected in the object reference.

You can create your own int class that will have this behavior if you desire.

Edited by Momerath: n/a


Say I have my Foo class

public class Foo
        public float a = float.MaxValue;

I create a list that can hold Foo classes.

List<Foo> foos = new List<Foo>(10);

I now add a foo instance to the list but then make it null.

Foo foo = new Foo();
            foo = null;

The foos list still contains the foo instance even though it is now null. Why is this the case?

Edited by DaveTran: n/a


Setting a reference to null doesn't get rid of the original object. I'm trying to come up with a good analogy, but this is the best I can do right now:

Let us say someone gives you their address [which is a form of reference] (Foo foo = new Foo()). You then copy that address into your address book (foos.Add(foo)). You then throw away the original copy of the address (foo = null). Does this erase your address book? No, you still have a reference to their address unless you get rid of it, also.

Edit: Wanted to add this: Given your class above:

Foo foo = new Foo();

foo.a = 3.4f;
Console.WriteLine("{0}", foos[0].a); // will display 3.4f
foo.a = 2.9f;
Console.WriteLine("{0}", foos[0].a); // will display 2.9f since the two references are the same

Edited by Momerath: n/a

Votes + Comments
great analogy

Is there no way to automatically link the two should the original become null?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.