I don’t think that at present it is possible, or if it’s even a good idea, but that’s what I was thinking now. I use MSTest to unit test my C # project. In one of my tests, I do the following:
MyClass instance; try { instance = getValue(); } catch (MyException ex) { Assert.Fail("Caught MyException"); } instance.doStuff(); // Use of unassigned local variable 'instance'
To compile this code, I need to assign the value of instance either in the declaration or in the catch . I could alternatively return after Assert.Fail , but this is still a workaround instead of the compiler, just knowing that execution cannot continue after this point. Assert.Fail never, as far as I know, allows execution, so instance will never be used without a value. Why then should I assign meaning to it? If I changed Assert.Fail to something like throw ex , the code compiles fine, I guess, because it knows that the exception will reject execution in order to go to the point where instance will be used uninitialized.
On the contrary, what if I do not want the test to fail, but rather designated as inconclusive? I could do Assert.Inconclusive instead of Fail , and it would be nice if the compiler knew that execution would not continue after that.
So, is this a case of runtime and compile-time knowledge of where execution will continue? Would it be reasonable if C # had some way of saying that a member, in this case Assert.Fail , would never allow execution after it returns? Perhaps this could be in the form of a method attribute. Would this be useful or unnecessary complexity for the compiler?
Outdoor unit tests
Since people [really] point out that this is a dumb way to write unit test, consider my question outside the scope of unit testing:
MyClass instance; if (badThings) { someMethodThatWillNeverReturn(); } else { instance = new MyClass(); } instance.doStuff();
Here, I could potentially replace the call to someMethodThatWillNeverReturn an exception, and perhaps if I had things, I could do this in the constructor for the exception.
Resharper Values
If I add return after Assert.Fail or Assert.Inconclusive , the colors of Resharper return grayed out and have a tooltip that says "The code is heuristically unavailable."