Deadly Nicotine Deadly Nicotine - 2 months ago 7
C# Question

In C#, how can I return what a property of an object refers to?

Let me explain what I mean. Say I have an object

public class Foo
{
public int Val { get; set; }
}


and another like

public class Bar
{
public Foo Reference { get; set; }
}


Let's say I have

Bar mybar = new Bar() { Reference = new Foo() { Val = 69 } }


and I want to temporarily set

mybar.Reference = null;


then set it back to what it previously was. Well, I can't do

var temp = mybar.Reference;
mybar.Reference = null;
mybar.Reference = temp;


because line 2 of the above sets
temp
to
null
. So how can I do what I'm trying to do?

Answer

No, you can do it, and it will work.

Reference types, as your Foo is, contains only "reference" to the actual object. So property Bar.Reference contain memory address to the actual object of Foo.

Your code:

var temp = mybar.Reference;

Code above will copy "memory address/reference" to variable temp.
Now both temp and mybar.Reference pointing to the same object in the memory.

mybar.Reference = null;

Code above set variable mybar.Reference to null, now mybar.Reference pointing "nowhere", but notice, that temp still have a reference to your original object.

mybar.Reference = temp;

Last line copy "memory address" from temp back to the mybar.Reference

Comments