Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to detect unreachable code or other built in compile warnings using Roslyn

Tags:

.net

roslyn

Is it possible to detect unreachable code or other built in compile warnings using Roslyn?

private void DoSomething()
{
     string a = "TEST";

     throw new Exception("Why would I throw an exception here?");

     a = "This will never be reached"; //this is a compile time warning for unreachable code...Can I detect it?

}

I've tried examining the node properties in Semantic and Syntax methods but didn't see any issues or warning collections.

like image 242
Jay Avatar asked Nov 26 '25 06:11

Jay


1 Answers

You can discover this using the semantic model's AnalyzeRegionControlFlow method. You call this passing in a text span that correspond to the statements you are interested in. AnalyzeRegionControlFlow will return you a data structure that has a property RegionEndPointIsReachable, it will also tell you all the statements that either jump into or out of the region.

If you want to know how to find the actual diagnostics that the compiler would report you need to use the GetDiagnostics method on the semantic model.

like image 140
Matt Warren Avatar answered Nov 27 '25 19:11

Matt Warren