0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【.NET 10対応】VB.NET基礎文法完全ガイド【図解×コード】

Posted at

🟦 VB.NET基礎文法完全ガイド【図解×コード】

📌 はじめに

この記事では、VB.NET(Visual Basic .NET)の基本文法を図解とコードで分かりやすく解説します。.NETでの開発を始めたい方、既存のVB.NETシステムを保守する方におすすめの内容です。

🖥️ VB.NETってどんな言語?

VB.NETは以下のような場面でよく使われます:

  • Windowsアプリケーション(Windows Forms)
  • Webアプリケーション(ASP.NET)
  • 業務システム(企業の基幹システム)
  • Officeアドイン(Excel、Wordの拡張)

🌍 VB.NETの特徴(図解)

⚠️ VB.NETの現状について

VB.NETは.NET 10でもサポートされていますが、メンテナンスモード(安定・保守状態)となっています。新機能の追加は限定的で、Microsoftは新規開発にはC#を推奨しています。既存システムの保守や、VB6からの移行先としては引き続き有効な選択肢です。


🧰 1. 開発環境の準備(.NET 10)

🔧 .NET SDKをインストールする

現在は .NET 10 が最新のLTS(長期サポート)版で推奨です(2028年11月までサポート)。

.NET と VB.NET のバージョン対応

.NET バージョン VB.NET バージョン サポート期限
.NET 10 VB 17.13 2028年11月(LTS)
.NET 9 VB 17.12 2026年5月
.NET 8 VB 17.11 2026年11月(LTS)
  • バージョン確認
    dotnet --version
    

エディタ

  • Visual Studio 2026(Windows向け統合開発環境・推奨)
  • Visual Studio Code + VB拡張機能(軽量・基本的な編集向け)

プロジェクトの作成

dotnet new console -lang VB -n MyApp
cd MyApp
dotnet run

📘 2. 変数と型

よく使う型一覧

説明
Integer 整数 10, -5
Double 小数 3.14
String 文字列 "Hello"
Boolean 真偽値 True / False

サンプルコード

Dim age As Integer = 30
Dim name As String = "Taro"
Dim isAdmin As Boolean = True

' 文字列補間($をつけると変数を埋め込めます)
Console.WriteLine($"Name: {name}, Age: {age}")

型推論

右辺から型が明らかな場合、型を省略可能です(Option Infer On が必要)。

Dim age = 30           ' Integer型と推論される
Dim name = "Taro"      ' String型と推論される

C# との型名対応

VB.NET C# 説明
Integer int 整数
Double double 小数
String string 文字列
Boolean bool 真偽値
Nothing null 値なし

🔀 3. 条件分岐(If / Select Case)

If 文

Dim age As Integer = 20

If age >= 20 Then
    Console.WriteLine("大人")
Else
    Console.WriteLine("子供")
End If

If 文(複数条件)

Dim score As Integer = 80

If score >= 90 Then
    Console.WriteLine("Excellent!")
ElseIf score >= 70 Then
    Console.WriteLine("Good!")
Else
    Console.WriteLine("Try again")
End If

Select Case 文(C# の switch に相当)

Dim n As Integer = 2

Select Case n
    Case 1
        Console.WriteLine("One")
    Case 2
        Console.WriteLine("Two")
    Case Else
        Console.WriteLine("Other")
End Select

Select Case 文(範囲指定)

VB.NETでは範囲を直感的に指定できます。

Dim age As Integer = 25

Select Case age
    Case 0 To 12
        Console.WriteLine("子供")
    Case 13 To 19
        Console.WriteLine("ティーンエイジャー")
    Case Is >= 20
        Console.WriteLine("大人")
End Select

🔁 4. 繰り返し(For / While / For Each)

For 文

For i As Integer = 0 To 4
    Console.WriteLine(i)
Next

For 文(ステップ指定)

' 2ずつ増加
For i As Integer = 0 To 10 Step 2
    Console.WriteLine(i)
Next

' 逆順(10から0へ)
For i As Integer = 10 To 0 Step -1
    Console.WriteLine(i)
Next

While 文

Dim i As Integer = 0
While i < 5
    Console.WriteLine(i)
    i += 1
End While

Do While / Do Until 文

' 条件が True の間繰り返す
Dim i As Integer = 0
Do While i < 5
    Console.WriteLine(i)
    i += 1
Loop

' 条件が True になるまで繰り返す
Dim j As Integer = 0
Do Until j >= 5
    Console.WriteLine(j)
    j += 1
Loop

For Each 文

配列やコレクションの要素を順番に取り出します。

Dim fruits() As String = {"Apple", "Banana", "Orange"}
For Each fruit As String In fruits
    Console.WriteLine(fruit)
Next

📦 5. 配列とコレクション

配列(Array)

サイズ固定です。

Dim nums() As Integer = {10, 20, 30}

For i As Integer = 0 To nums.Length - 1
    Console.WriteLine(nums(i))
Next

注意:VB.NETでは配列のインデックスに () を使います(C# は [])。

List(動的配列)

サイズが可変で便利です。

Imports System.Collections.Generic

Dim nums As New List(Of Integer) From {10, 20, 30}

' 追加
nums.Add(40)

' 削除
nums.Remove(20)

' 表示
For Each n As Integer In nums
    Console.WriteLine(n)
Next

Dictionary(連想配列)

キーと値のペアで管理します。

Imports System.Collections.Generic

Dim scores As New Dictionary(Of String, Integer) From {
    {"Taro", 85},
    {"Hanako", 92}
}

' 追加または更新
scores("Jiro") = 78

' 表示
For Each pair In scores
    Console.WriteLine($"{pair.Key}: {pair.Value}")
Next

🧩 6. メソッド(Sub / Function)

VB.NETでは、戻り値のないメソッドを Sub、戻り値のあるメソッドを Function と呼びます。

Sub(戻り値なし)

Sub SayHello(name As String)
    Console.WriteLine($"Hello, {name}!")
End Sub

' 呼び出し
SayHello("Taro")

Function(戻り値あり)

Function Add(a As Integer, b As Integer) As Integer
    Return a + b
End Function

' 呼び出し
Dim result As Integer = Add(3, 5)
Console.WriteLine($"Result: {result}")

デフォルト引数(Optional)

Sub Greet(Optional name As String = "Guest")
    Console.WriteLine($"Hello, {name}!")
End Sub

' 呼び出し
Greet()        ' Hello, Guest!
Greet("Taro")  ' Hello, Taro!

名前付き引数

Sub PrintInfo(name As String, age As Integer)
    Console.WriteLine($"{name} is {age} years old")
End Sub

' 引数の順序を気にせず呼び出し可能
PrintInfo(age:=25, name:="Taro")

🧱 7. クラスとオブジェクト

Class Person
    Public Property Name As String
    Public Property Age As Integer

    Public Sub SayHello()
        Console.WriteLine($"こんにちは、{Name}です")
    End Sub
End Class

' 使用例
Module Program
    Sub Main()
        Dim p As New Person() With {
            .Name = "Taro",
            .Age = 20
        }
        p.SayHello()
    End Sub
End Module

コンストラクタ

Class Person
    Public Property Name As String
    Public Property Age As Integer

    ' コンストラクタ
    Public Sub New(name As String, age As Integer)
        Me.Name = name
        Me.Age = age
    End Sub

    Public Sub SayHello()
        Console.WriteLine($"こんにちは、{Name}です")
    End Sub
End Class

' 使用例
Dim p As New Person("Taro", 20)
p.SayHello()

🎯 8. プロパティとフィールド

自動実装プロパティ

最もシンプルな形式です。

Public Property Age As Integer

カスタムロジック付きプロパティ

入力チェックなどのロジックを追加する場合は、バッキングフィールドを定義します。

Class Person
    Private _name As String = String.Empty

    Public Property Name As String
        Get
            Return _name
        End Get
        Set(value As String)
            ' 前後の空白を除去
            _name = If(value?.Trim(), String.Empty)
        End Set
    End Property
End Class

読み取り専用プロパティ

Public ReadOnly Property FullName As String
    Get
        Return $"{FirstName} {LastName}"
    End Get
End Property

' または簡潔に(自動実装)
Public ReadOnly Property CreatedAt As DateTime = DateTime.Now

⏳ 9. 非同期処理(Async/Await)入門

Async/Awaitを使うと、時間のかかる処理を効率的に扱えます。

Imports System.Net.Http
Imports System.Threading.Tasks

Module Program
    Async Function Main() As Task
        Dim content As String = Await FetchDataAsync("https://example.com")
        Console.WriteLine($"取得したデータの長さ: {content.Length}")
    End Function

    Async Function FetchDataAsync(url As String) As Task(Of String)
        Using client As New HttpClient()
            Return Await client.GetStringAsync(url)
        End Using
    End Function
End Module

ポイント

  • Async:このメソッドは非同期処理を含むことを示す
  • Await:非同期処理の完了を待つ(スレッドをブロックしない)
  • Task / Task(Of T):非同期処理の戻り値の型

⚠️ 10. 例外処理

Try
    Dim a As Integer = 10
    Dim b As Integer = 0
    Dim result As Integer = a \ b  ' 整数除算
Catch ex As DivideByZeroException
    Console.WriteLine($"エラー:{ex.Message}")
Finally
    Console.WriteLine("処理完了")  ' エラーの有無に関わらず実行
End Try

複数の例外をキャッチ

Try
    ' 何らかの処理
Catch ex As ArgumentNullException
    Console.WriteLine("引数がNullです")
Catch ex As InvalidOperationException
    Console.WriteLine("無効な操作です")
Catch ex As Exception
    Console.WriteLine($"予期しないエラー:{ex.Message}")
End Try

カスタム例外

Class CustomException
    Inherits Exception

    Public Sub New(message As String)
        MyBase.New(message)
    End Sub
End Class

' 使用例
Throw New CustomException("カスタムエラー")

🔄 C# との構文比較

項目 VB.NET C#
変数宣言 Dim x As Integer = 10 int x = 10;
条件分岐 If ... Then ... End If if (...) { ... }
繰り返し For i = 0 To 4 ... Next for (int i = 0; i < 5; i++)
メソッド(戻り値なし) Sub void
メソッド(戻り値あり) Function ... As 型 型 メソッド名()
Null値 Nothing null
論理演算子(短絡評価) AndAlso / OrElse && / ||
文字列結合 & または + +
コメント ' または REM // または /* */

🎉 まとめ

本記事では、VB.NETの基本文法を図解とコードで解説しました。

  • 開発環境:.NET 10 SDKの準備
  • 基本構文:変数、条件分岐、ループ
  • データ構造:配列、List、Dictionary
  • メソッド:Sub(戻り値なし)、Function(戻り値あり)
  • オブジェクト指向:クラス、プロパティ
  • 非同期処理:Async/Await
  • 例外処理:Try-Catch-Finally

VB.NETの今後について

VB.NETは.NET 10でも引き続きサポートされていますが、メンテナンスモードとなっており、新機能の追加は限定的です。新規プロジェクトにはC#が推奨されていますが、既存のVB.NETシステムの保守や、VB6からの移行先としては有効な選択肢です。

次のステップ

  1. LINQでデータ操作を簡潔にする方法を学ぶ
  2. Windows Formsでデスクトップアプリを作成する
  3. ASP.NET CoreでWeb開発に挑戦する
  4. C#への移行を検討する(新規開発向け)

これからVB.NETを学ぶ方、既存システムを保守する方の参考になれば嬉しいです!
参考になったら「いいね」👍 お願いします!

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?