Basically, can I do this, and what actually happens?
public class foo
{
public int id;
public void bar()
{
//do stuff
this = null; // ?
//do stuff
foo[] all = otherclass.FindAllFoos();
foreach(foo f in all)
{
if(f.id == 42)
{
this = f; // ?
break;
}
}
//do stuff
}
};
Some specific background that shouldn’t matter:
The real project has a class that represents a USB device that I’m currently talking to, and just before this point in the program, I tell the device to reboot. When the device comes back, it appears different enough to invalidate this instance, so I have to find it again among all the connected devices and continue talking to it.
6
In C#, you cannot make an instance set itself to null. this = null;
will not work. The functions and data that are defined inside of a class “live” in that classes instance. If the instance is destroyed, everything associated with it is destroyed.
The bar()
method should be moved into a different class, and manipulate foo
classes. For example:
public class FooManipulator
{
private Foo _myFoo;
public void bar()
{
var allTheFoos = otherClass.FindAllFoos();
foreach(foo f in all)
{
if(f.id == 42)
{
this._myFoo = f;
break;
}
}
}
}
this=null
You cannot assign to this
, it’s read only for classes.
You can assign to this
for a struct, but then a struct can’t be null because its a value type.
Try putting it in an IDE?
0