January 31, 2016

Unreachable code affects the result

"Can unreachable code affects the result?" - it's very tricky question. I sure your first answer will be "No". Because it is too natural. Unreachable code means, that this code never be executed. But let's  have a look on such example:
using System;
using static System.Console;

namespace UnreachableCodeExample
{
 internal class Program
 {
  private static void Main()
  {
   F(() =>
   {
    return 10;
    return 10.123;
   });
  }

  private static void F(Func<int> f)
  {
   WriteLine(f.Invoke() + " Integer");
  }

  private static void F(Func<double> f)
  {
   WriteLine(f.Invoke() + " Double");
  }
 }
}

IDE gives us a hint, that second return is redundant.

Well, compile the code and see the result
Very interesting. We've got right result with incorrect type. Why it happened? Looks like unreachable code affects our result. To test this hypothesis let's try another example.
using System;
using static System.Console;

namespace UnreachableCodeExample
{
 internal class Program
 {
  private static void Main()
  {
   F(() =>
   {
    return (byte)10;
    return (int)10;
   });
  }

  private static void F(Func<byte> f)
  {
   WriteLine(f.Invoke() + " Byte");
  }

  private static void F(Func<int> f)
  {
   WriteLine(f.Invoke() + " Integer");
  }
 }
}
Now we expect to see "10 Integer".

Yes, that's it. So we can definitely say, that compiler analyzes all return types, regardless their location and choose the biggest one as a returning type for lambda function.

In our example it would lead to unintended consequences, so be careful with such constructions. And happy coding!

1 comment: