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?

E.g.

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?

Recommended Answers

All 6 Replies

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.

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();
            foos.Add(foo);
            foo = null;

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

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();
foos.Add(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
commented: great analogy +3

Momerath is right, just copy this

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

Not without writing a wrapper class to deal with this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.