佐々木屋

技術的なことから趣味まで色々書きます

VB.NETでブロック文を作成したい

C#には構造文を作る区切り文字「{ }」があります。

{
    string hoge = "piyo";
    Console.WriteLine(hoge);
}

{
    int hoge = 123;
    Console.WriteLine(hoge);
}

こんな感じで局所的に変数を作ったり、処理を分けたりするのにすごく便利なのです。お馴染みのforやIfなどの構造文同様で変数スコープはその内側だけになり、string型の変数「hoge」とint型の変数「hoge」は別物となります。

しかしVB.NETには同じ機能がありません。が、似たようなことは出来ます。

要は既存の機能を流用して無理やり構造化してしまえばよいわけです。

If True Then
    Dim hoge As String = "piyo"
    Console.WriteLine(hoge)
End If

If True Then
    Dim hoge As Integer = 123
    Console.WriteLine(hoge)
End If

又は、

With Nothing
    Dim hoge As String = "piyo"
    Console.WriteLine(hoge)
End With

With Nothing
    Dim hoge As Integer = 123
    Console.WriteLine(hoge)
End With

if文を利用した場合だと、本当のif文と混同してしまうので、私は後者の書き方を使っています。