You can check if an object is null but can you check if an object is valid?
Assert.IsValid(object_name);
For example, the object has been deleted by the garbage collector or someone has done dispose on it. But the pointer is still pointing to that object.
If the object has been freed by the garbage collector, you won’t have a reference to it, by definition.
If it’s been disposed and that’s important to the object’s validity, the type ought to provide a way of determining that. (In some cases
Disposecan just mean “reset”, for example.)It’s rarely appropriate to even allow the possibility of having a reference to a disposed object though – if you use:
then the object will be disposed at the same time that
foogoes out of scope, so this isn’t an issue.