I've been looking for this info for a loooong time. Never seen anyone asking stuff like this before. I know that we can use pointer in C# inside unsafe code, but thats not the case. The problem is:
MyClass beta = new MyClass();
MyClass alpha = beta;
beta = null;
What I need to do now is set beta to null and ALSO set alpha to null. Let's say that i have returned alpha in a function, so I dont have access to it anymore, so, how can I set it to null? In c++ if beta and alpha were pointer I could just free the memory that beta points to, but I dont know a way to do that in c#.
In a more basic way, lets say that I have to set both variables to null, but i have acces only to one of them.
Edit
I did see some answers that have nothing to deal with the question i did... Ill try to explain again.
I'm creating a class that do some motion effect and return a instance that can be used to pause or stop this motion.
The programmers that use this class are used to test variables with if(variable != null)
before using it.
What i need is when the motion is over the instance they have is turned into null, so they know that its not usefull anymore.
Is there any way of doing it?
You need to add an additional layer of indirection. To put things in C++ terms, MyClass
is a pointer to an object, so to set both pointers to null you need to be passing around pointers to pointers instead, so that you can resolve the pointer to pointer to just a pointer, set that to null, and both double pointers will resolve to null
.
Adding an extra layer of indirection in C# usually means creating a new class.
public class Wrapper<T>
{
public T Value { get; set; }
}
Using that, we can make alpha
and beta
each be Wrapper<MyClass>
objects (make sure they are both the same instance of Wrapper
), and to affect both "pointers" you can just set Value
of the Wrapper
to null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With