Public Group

# problem with references!

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

## 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; }
set { collection = value; }  /* Should do: collection 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 = e;    //collection 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 on other sites
Basically, in C#, references can only live on the stack. You can't store a reference in a class, only a copy of what it references.

##### Share on other sites
Maybe I can use boxing? Have a reference type reference to a reference type.

##### 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 = e;" (that's an lvalue copy, that's why j was 1)

##### 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]

1. 1
2. 2
3. 3
Rutin
16
4. 4
5. 5

• 10
• 10
• 14
• 10
• 25
• ### Forum Statistics

• Total Topics
632647
• Total Posts
3007640
• ### Who's Online (See full list)

There are no registered users currently online

×