0

In c# I was wondering if there was any way to have a reference not allow what its referencing to migrate to the reference. Here's some FAKE c# code to illustrate what I mean:

class foo  {}

class bar
{
    public locked foo Foo; //of course locked doesn't actually exist
}

void main()
{
    foo myFoo = new foo();
    bar myBar == new bar();
    myBar.Foo = myFoo;

    myFoo = null

    if (myBar.Foo == null)
    {
        println("foo = null");
    }
}

//will print "foo = null"

obviously this won't compile, and when you delete foo it would just migrate to myBar.Foo, which I don;t want to happen

Taura J Greig
  • 105
  • 2
  • 7
  • I don't get what "migrate to the reference" is supposed to mean here. – H H Jan 12 '13 at 21:43
  • 1
    Not clear on what you mean by "migrate". Did you look at the `const` and `readonly` keywords? – Oded Jan 12 '13 at 21:43
  • If I understand the code, you are looking for a way to not allow the reference to a variable to change once initially set? – Oded Jan 12 '13 at 21:45
  • Or do you mean you want a _deep clone_ of `foo`, instead of the reference that `myBar.Foo` to be the same as to `myFoo`? – Oded Jan 12 '13 at 21:47

2 Answers2

1
myBar.Foo = myFoo;

myFoo = null

Doing myFoo = null doesn't make myBar.Foo null. It will still reference to the old object.

Fields can be ref in chsarp, and there is not getting around this. Better explanation can be found here - How do I assign by "reference" to a class field in c#?

Community
  • 1
  • 1
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • thats what I don't want trying to prevent, I want myBar.Foo to only reference the old object if it is currently referenced by myFoo. When myFoo is set to null the object doesn't move to myBar.Foo, instead myBar.Foo will give me null because it can't find the object. Thats what I want to happen, kind of like a pointer. hmm, but will defeat the purpose of c# wont it. – Taura J Greig Jan 12 '13 at 22:47
0

What you seem to want is not possible, at least directly. I will describe what I think you want for other readers here because the term "migrate" is non-standard and confusing.

Let's describe what myBar.Foo = myFoo is doing. It is saying that the storage location called Foo on myBar points to the object currently occupying the storage location in the local myFoo. What you seem to want is myBar.Foo acting as an alias (i.e. another name) for the storage location myFoo.

Eric Lippert has an excellent answer to a similar question posted here, which describe why this is not allowed and what to do instead. He describes, what is sometimes called a "lens", a construct that captures getter and setter methods into a single object and passes a reference to that around.

Community
  • 1
  • 1
Mike Zboray
  • 39,828
  • 3
  • 90
  • 122