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!

7 comments:

  1. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. psc result marksheet

    ReplyDelete
  2. Your blog very important information together. all thanks for share this post. PSC Result 2019

    ReplyDelete
  3. this post has been of great help to me. thanks. BD Govt Jobs

    ReplyDelete
  4. 20 Public General, Science and Technology University will publish the GST primary selection result on Very Soon. According to the news, Guccho Admission Result will be published gstadmission.ac.bd. also check- NID Card Online Copy
    sorkari chakrir khobor 2021 in our website.
    All Source Find- jobnewsbd24.com/sitemap

    ReplyDelete
  5. Stainless steel - Titanium Art
    A titanium 4000 stainless steel core does titanium set off metal detectors with an 2018 ford fusion hybrid titanium index of 100 pcs iron titanium token of thickness. Injecting steel. Titanium is an alloy trekz titanium headphones used in traditional ceramics. Ceramic.

    ReplyDelete