C# Puzzle : Reachable goto pointing to an unreachable label

半腔热情 提交于 2019-11-29 07:58:10

My original answer:

    try
    {
        goto ILikeCheese;
    }
    finally
    {
        throw new InvalidOperationException("You only have cottage cheese.");
    }
ILikeCheese:
    Console.WriteLine("MMM. Cheese is yummy.");

Here is without the compiler warning.

    bool jumping = false;
    try
    {
        if (DateTime.Now < DateTime.MaxValue)
        {
            jumping = (Environment.NewLine != "\t");
            goto ILikeCheese;
        }

        return;
    }
    finally
    {
        if (jumping)
            throw new InvalidOperationException("You only have cottage cheese.");
    }
ILikeCheese:
    Console.WriteLine("MMM. Cheese is yummy.");
Kerem Kusmezer

By the way if you use goto the csharp compiler for example for this case without finally block changes the code to a version without goto.

using System;
public class InternalTesting
{
public static void Main(string[] args)
{
  bool jumping = false;
    try
    {
        if (DateTime.Now < DateTime.MaxValue)
        {
            jumping = (Environment.NewLine != "\t");
            goto ILikeCheese;
        }
    else{
            return;
    }
    }
    finally
    {
        if (jumping)
{
            //throw new InvalidOperationException("You only have cottage cheese.");
    Console.WriteLine("Test Me Deeply");
}
    }
ILikeCheese:
    Console.WriteLine("MMM. Cheese is yummy.");
}
}

Turns To:

public static void Main(string[] args)
{
    bool flag = false;
    try
    {
        if (DateTime.Now < DateTime.MaxValue)
        {
            flag = Environment.NewLine != "\t";
        }
        else
        {
            return;
        }
    }
    finally
    {
        if (flag)
        {
            Console.WriteLine("Test Me Deeply");
        }
    }
    Console.WriteLine("MMM. Cheese is yummy.");
}
goto cant_reach_me;

try{
cant_reach_me:
}
catch{}

This is either a compile or runtime error, I can not remember. The label must be outside the try/catch block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!