Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#7以降でお手軽に多重ループを抜ける

Last updated at Posted at 2019-11-08

C#7以降でお手軽に多重ループを抜ける方法です。
C#ではgotoを除けば多重ループを抜ける構文がなく、フラグ用変数を使用するか、該当部分を関数化するして対応してきました。
わざわざ関数化するにしても煩わしさを感じていたわけですが、ローカル関数を使用するとお気楽に多重ループを抜けることが出来ます。

private void function() 
{
     int counter = 0;
     // do something here

     // 多重ループをローカル関数で囲う
     void DoIt()
     {
        while(true)
        {
            while(true)
            {
                // ローカル変数をそのまま参照できる!
                counter++;
                // Return文でローカル巻子を抜ける = 多重ループを抜ける
                if(counter >= 10) return;
            }
        }
    }
    // ローカル関数を実行
    DoIt();
    // do some other things here
    // 結果
    Console.WriteLine($"counter={counter}");
}

このように徒然なるまま書いたコードに数行足すだけで簡単に
多重ループを抜けることが出来ました。

ローカル関数を定義しただけで実行文を書くのを忘れたりするので注意。
JavaScriptのように関数の即時実行が出来たらいいんですが。

以上、スタジオへお返しします。

4
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Comments

No comments

Let's comment your feelings that are more than good

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?