I am trying to add some Dispose cleanup in a large hierarchy where the default dispose method used to do nothing. When I do so, I get very rare and difficult to reproduce bugs that make me suspect that I have a use after dispose bug somewhere in the large codebase, that went latent for years, because the dispose methods that used to do nothing now do things. I am not sure even which class causes the bug.
I am wondering if there is any way I can not only dispose of an arbitrary class, but then poison it so that anyone who touches that class in the future is immediately going to make something terrible (and catchable) happen. I am confident that if I could find the first use after the dispose I could easily work backward to the dispose. Right now, I just know that something bad happens sometimes, and not even every time I run the test.
I recognize that I am working against the language here because C# tries very hard to keep everything type safe. I know this is bad C#, but it’s just for some test code. I am not above reflection, or unsafe code, or breaking other rules to make this happen. I would like to put an arbitrary object into such a bad state that doing anything with it is a fatal error.
Notice I need to poison the object, not the reference to the object. Poisoning a reference is easy — just set it to null.
Notice also that if this were a small hierarchy, I could just add an “am I disposed” flag and check it at every method entrance. Unfortunately, I am at the root of a very large hierarchy, so this is not a reasonable solution to the problem right now.