1

When writing code, I'll quite often temporarily inject random exceptions to ensure error flow is as expected.

eg

public void SomeFunc()
{
   Console.WriteLine("Some code");

   throw new Exception("BOOOOM!"); //added temporarily

   Console.WriteLine("Some more code");
}

The problem is I have warnings set as errors, so compilation will fail with a CS0162 Unreachable code detected, since "Some more code" will never run.

So just add a condition you say:

public void SomeFunc()
{
   Console.WriteLine("Some code");

   if (true)
       throw new Exception("BOOOOM!"); //added temporarily

   Console.WriteLine("Some more code");
}

but no, this compiler is clever enough to note that the condition will always be true, and flags a CS0162 again.

I generally end up with the following:

public void SomeFunc()
{
   Console.WriteLine("Some code");

   var debug = true;
   if (debug)
       throw new Exception("BOOOOM!"); //added temporarily

   Console.WriteLine("Some more code");
}

So my idle question, since I'm lazy, is whether there's a simpler way to fool the compiler? A one liner would be perfect.

(And yes, I do write unit tests eventually ;)

GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103

2 Answers2

2

Here's a two-liner. Resharper suggested and did this for me. Otherwise remembering it would be all but impossible.

    throw new Exception("Boo!");

#pragma warning disable 162

    // The unreachable code is here            

#pragma warning restore 162

While that's a direct answer, I probably wouldn't do that because it's clunky.

You can also change the severity of the error so that it compiles with a warning. That's my default setting.

The specifics of how to do that vary with the Visual Studio version. Here's the documentation.

In Visual Studio 2019 you would add or modify this in your .editorconfig file:

[*.cs]

# CS0162: Unreachable code detected
dotnet_diagnostic.CS0162.severity = warning
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
  • Ah! Didn't realise you could set individual severity at a global level. That's very useful thanks. That being said I'll probably leave it on since I do want to be informed about genuine cases. – GazTheDestroyer Apr 15 '20 at 08:22
1

The compiler is rather dumb, in fact. It generally doesn't recognise non-constant expressions. This means that you just need to create a condition that is always true, with at least one non-constant expression.

I'm sure that after reading the link, you can come up with loads of these. Here's an example:

if ("a".Length == 1) throw new Exception("...");
Sweeper
  • 213,210
  • 22
  • 193
  • 313