Reputation: 3391
I know this is possible to have a reference to another object in a method by using ref
keyword. Created object in the following example inside the method is also available outside of the method.
public Method(ref OtherClass input)
{
input = new OtherClass();
}
But I need to get one step ahead. I need to hold the reference as a property in my object and change the original object whenever I want in other methods in future.
public class CLass1
{
OtherClass _input;
public Bind(ref OtherClass input)
{
input = new OtherClass(); // instantiating the object
_input = input; // keeping a reference of the created object for later usage!
}
public void Unbind()
{
_input = null;
}
}
When I Bind
the object the original object initialized with a new object and this is exactly what I want. But after that I run Unbind()
only the _input
becomes null and input
remains intact. I need the input
becomes null too! How is that possible?
Upvotes: 0
Views: 3102
Reputation: 726579
This will not work, because ref
is meaningful only as a parameter of a method. You cannot store a reference beyond the scope of a method, because you do not know about the scope of the variable that was passed by reference into your method. For example, think what would happen if you do this:
class WithRef {
// Imagine you can do this
public ref OtherClass other;
public WithRef(ref OtherClass other) {
this.other = other;
}
}
Now let's say you do this:
WithRef MakeRef() {
OtherObject variable;
return new WithRef(ref variable);
}
void Test() {
var invalid = MakeRef();
}
At this point invalid
references a local variable inside MakeRef
method, which is out of scope.
Upvotes: 0
Reputation: 7474
public abstract class SelfRefType
<T extends< SelfRefType<T>> {
private OtherType<T>_ref;
protected abstract T getThis();
public void set() {
_ref.m( getThis() ); }
}
public interface OtherType<E> {
void m(E arg);
}
public Subtype extends
SellfRefType<Subtype> {
protected Subtype getThis() {
return this; }
}
Upvotes: 0
Reputation: 475
It is not possible to do exactly the thing that you are asking, but you can achieve the functionality if you wrap your OtherClass with WrapperClass
public class WrapperClass
{
public OtherClass Input;
}
public class CLass1
{
WrapperClass _wrapper;
public Bind(ref WrapperClass wrapper)
{
wrapper = new WrapperClass();
wrapper.Input = new OtherClass(); // instantiating the object
_wrapper = wrapper; // keeping a reference of the created object for later usage!
}
public void Unbind()
{
_wrapper.Input= null;
}
}
Upvotes: 1