#15 – C# goto Statement

The notorious goto statement, enables you to jump to a labeled statement.

using System;

goto lable1;

Console.WriteLine("This won't be executed.");

lable1:
Console.WriteLine("This will be executed.");

Console.WriteLine("Hello World!");

You will get compile warning that:

Program.cs(5,1): warning CS0162: Unreachable code detected 

Ignore the warning and run the program, you will get the output:

This will be executed.
Hello World!

Key Points

  • Cannot jump out of a class.
  • Cannot jump into a block of code since goto and the label have to be in the same scope.
  • Cannot exit a finally block after try ... catch block.

Summary

I believe that few developers like to use goto statement in their projects.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.