Sign in to follow this  

problem with references!

This topic is 3376 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Thanks for reading. I'm Remy.
class SafeArray<ElementType> where ElementType : class
    {
        ElementType[] collection;

        public SafeArray(int size) { collection = new ElementType[size]; }
        public SafeArray(ElementType[] cpar) { collection = cpar; }

        public ElementType this[int i]
        {
            get { return collection[i]; }
            set { collection[i] = value; }  /* Should do: collection[i] was referring to a reference type.
                                             * now it refers to the same reference type, although the value of 
                                             * the reference type has changed: the reference type refers to
                                             * something else now.
                                             * 
                                             * but it seems that it doesn't do this!
                                             */
        }

        public void Set(ref ElementType e, int i)
        {
            collection[i] = e;    //collection[i] now refers to the same reference type as e.
        }
    }

    class Test
    {
        static public void test()
        {
            SafeArray<object> a = new SafeArray<object>(1);
            int i = 1;
            object o = i;
            a.Set(ref o, 0);
            int i2 = 2;
            object o2 = i2;
            a[0] = o2;
            int j = (int)o;
                                     //j was 1, but I want it to be 2. 
        }
    }

Share this post


Link to post
Share on other sites
Also your class SafeArray stores a collection of ElementType by value not by reference "ElementType[] collection;"
so you will never be able to store any references into it anyway, even when you do this "collection[i] = e;" (that's an lvalue copy, that's why j was 1)

Share this post


Link to post
Share on other sites
Hmm.. so in summary: I can never change a reference.
And I can't store a reference of a reference.

If I have a reference and I want to change the object it refersw to then I am forced to access the current object and use one of its methods to change it.

[Edited by - steenreem on September 15, 2008 11:23:23 AM]

Share this post


Link to post
Share on other sites

This topic is 3376 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this