4

I have a .NET project (C#), where in my code there's a function like this:

public void myFunction(string myStr)
{
   myStr = "This is not an empty string";

   if(String.IsNullOrEmpty(myStr))
   {
       DoSomething();
   }
}

I want to analyze my application to see if there are blocks of code that can never be reached. How could I do this?

Nick
  • 10,309
  • 21
  • 97
  • 201

3 Answers3

1

Use ReSharper to make your code more efficient. Checking of unavailable code areas in one of it's features.

Johnny_D
  • 4,592
  • 3
  • 33
  • 63
  • Does this handle OP's example? – Ira Baxter May 28 '12 at 19:57
  • Just checked code given in topic, was suprized, but resharper was silent, and no warning given. Though still it remains most useful tool for code quality for me. – Johnny_D May 29 '12 at 07:26
  • So, I understand resharper is generally useful to you, but why does that make resharper the answer to OPs question? – Ira Baxter May 29 '12 at 08:14
  • Cuz main question was "I want to analyze my application to see if there are blocks of code that can never be reached. How could I do this?" If resharpers isn't useful in one case, that doesn't make in bad tool for whole application examination. That's not an adv. – Johnny_D May 29 '12 at 08:24
1

To do this in general, you need a symbolic analysis of the values along all control paths, and boolean symbolic simplification to determine if the condition is true. For example:

void bar(...a) {
  ...
  x=2*a;
  if (...)  x=17;
  foo(x)
  ...
}
void foo(int x) {
  if (x<a && !x>5) { // dead code if called from bar ...
  ...

To know that the dead code line is really dead, you have to find all calls to foo and verify that each one causes this condition to occur. So you need a global call graph, for which you need global function pointer analysis, for which you need global and thus local points-to analysis...

I don't know any off-the-shelf tools that do this.

One could be built with some effort with a program transformation system. Our DMS Software Reengineering Toolkit has all of the mentioned machinery available for C. While all this machinery isn't yet available for C#, it is implemented in largely a langauge agnostic way so getting there for C# is sweat but not impractical.

Ira Baxter
  • 93,541
  • 22
  • 172
  • 341
-1

you may want to use tools like ReSharper which can do code quality analysis while developing. it gives you warnings like "code is heuristically unreachable"

sithereal
  • 1,656
  • 9
  • 16