変数、型と演算子
変数宣言と組み込み型
VB.NETはDim宣言で静的型付けされます。一般的な型:String、Integer(32ビット)、Long(64ビット)、Double(64ビット浮動小数点)、Decimal(金融用高精度)、Boolean、Date、Char。型サフィックス(DecimalはD、SingleはF、LongはL)でリテラル型を強制。Option Explicit Onが変数宣言を強制(タイプミスを防止)。Option Infer Onが明示的型なしのDimで型推論を有効化。Null許容型(Integer?)が値型をラップしNothingを保持可能 — データベースとAPIに便利。
' Option Explicit On -- requires declaration (recommended)
Module Variables
Sub Main()
Dim name As String = "Alice" ' text
Dim age As Integer = 30 ' 32-bit integer
Dim salary As Decimal = 50000.50D ' precise money
Dim pi As Double = 3.14159 ' 64-bit float
Dim isDev As Boolean = True ' True/False
Dim letter As Char = "A"c ' single character
Dim today As Date = #2024-06-18# ' date literal
' type inference (Option Infer On)
Dim count = 10 ' inferred as Integer
Dim message = "Hello" ' inferred as String
' nullable types (Value types that can be Nothing)
Dim score As Integer? = Nothing
If score.HasValue Then Console.WriteLine(score.Value)
' varType() returns the Type object
Console.WriteLine(name.GetType().Name) ' String
End Sub
End Module定数、列挙型と構造体
Constがコンパイル時定数を宣言(暗黙的にShared、変更不可)。Enumが名前付き整数定数を定義 — [Enum].Parseで文字列を変換、CIntで数値を取得。ブラケット表記[Error]は予約語をエスケープ。<Flags>属性がenumをビットフィールドとしてマークし、Or/And演算子で組み合わせを許可 — 権限とオプションに一般的。フラグにはビット幅を制御するため基になる型(As Integer)を常に指定。
' constants (compile-time, implicitly Shared)
Public Const Pi As Double = 3.14159265358979
Public Const MaxRetries As Integer = 3
' enum: named integer constants
Public Enum LogLevel
Debug = 0
Info = 1
Warning = 2
[Error] = 3 ' brackets for reserved words
End Enum
Module EnumsDemo
Sub Main()
Dim level As LogLevel = LogLevel.Warning
Console.WriteLine(level) ' Warning
Console.WriteLine(CInt(level)) ' 2
' parse string to enum
Dim parsed = [Enum].Parse(GetType(LogLevel), "Info")
Console.WriteLine(parsed) ' Info
' Flags attribute for bit-field enums
Dim perms As FilePermission = FilePermission.Read Or FilePermission.Write
If (perms And FilePermission.Read) <> 0 Then
Console.WriteLine("Has read")
End If
End Sub
End Module
<Flags>
Public Enum FilePermission As Integer
None = 0
Read = 1
Write = 2
Execute = 4
End Enum型変換とキャスト
拡大変換(IntegerからDouble)は暗黙的で安全。縮小変換(DoubleからInteger)は明示的キャストが必要。CInt/CStr/CDate/CDecはVBの変換関数(CTypeは汎用版)。DirectCastは最も厳密 — ランタイム型が完全に一致する場合のみ動作。TryCastは失敗時に例外をスローせずNothingを返す(参照型のみ)。ユーザー入力には例外を避けるためParseよりTryParseを推奨。IsNumeric/IsDateは便利な検証ヘルパー。CIntは丸め(銀行家丸め)、Int()は切り捨て。
' widening conversions (implicit, safe)
Dim i As Integer = 42
Dim d As Double = i ' Integer -> Double (no data loss)
' narrowing conversions (explicit, may lose data)
Dim d2 As Double = 3.99
Dim i2 As Integer = CInt(d2) ' 4 (rounds, not truncates)
Dim i3 As Integer = Int(d2) ' 3 (floor)
Dim s As String = CStr(42) ' "42"
Dim n As Integer = CInt("100") ' 100 (throws if invalid)
' DirectCast vs CType vs TryCast
Dim obj As Object = "Hello"
Dim s2 As String = DirectCast(obj, String) ' strict, same type only
Dim s3 As String = CType(obj, String) ' flexible, converts
' TryCast: returns Nothing if cast fails (reference types only)
Dim s4 As String = TryCast(obj, String)
If s4 IsNot Nothing Then Console.WriteLine(s4)
' conversion functions
Dim b As Boolean = CBool(1) ' True
Dim dt As Date = CDate("2024-06-18")
Dim dec As Decimal = CDec("99.99")
' IsNumeric, IsDate checks
If IsNumeric("42") Then Console.WriteLine("is number")
If IsDate("2024-06-18") Then Console.WriteLine("is date")
' Parse vs TryParse (safer)
Dim num As Integer
If Integer.TryParse("123", num) Then
Console.WriteLine(num) ' 123
End If演算子と式
VBは整数除算に\、実数除算に/を使用(/と%を使用するC#と異なる)。Modが剰余演算子。VBは代入と等価比較の両方に=を使用(コンテキストが決定)。And/Orは両オペランドを評価;AndAlso/OrElseは短絡(パフォーマンスとnull参照回避に推奨)。&が文字列連結演算子(数値加算もできる+ではない)。デフォルトでAndAlso/OrElseを使用して短絡し、Nothingオブジェクトのチェックなどのエラーを回避。
' arithmetic
Dim a As Integer = 10
Console.WriteLine(a + 3) ' 13
Console.WriteLine(a - 4) ' 6
Console.WriteLine(a * 2) ' 20
Console.WriteLine(a / 3) ' 3.333 (Double, real division)
Console.WriteLine(a \ 3) ' 3 (integer division)
Console.WriteLine(a Mod 3) ' 1 (remainder)
Console.WriteLine(a ^ 2) ' 100 (exponent)
' comparison (return Boolean)
Console.WriteLine(5 > 3) ' True
Console.WriteLine(5 = 5) ' True (VB uses = for equality)
Console.WriteLine(5 <> 4) ' True (not equal)
Console.WriteLine("a" < "b") ' True (string comparison)
' logical operators
Dim x As Boolean = True
Dim y As Boolean = False
Console.WriteLine(x And y) ' False (evaluates both)
Console.WriteLine(x Or y) ' True
Console.WriteLine(Not x) ' False
Console.WriteLine(x Xor y) ' True (exclusive or)
Console.WriteLine(x AndAlso y) ' False (short-circuit)
Console.WriteLine(x OrElse y) ' True (short-circuit)
' bitwise (on integers)
Console.WriteLine(5 And 3) ' 1 (0101 And 0011 = 0001)
Console.WriteLine(5 Or 3) ' 7
Console.WriteLine(5 Xor 3) ' 6
' string concatenation
Dim s As String = "Hello" & " " & "World" ' & operator
Dim s2 As String = $"Hello {a}" ' interpolation入力、出力とフォーマット
Console.WriteLine/Writeが基本出力メソッド。文字列補間($"...")が式を埋め込む現代的で読みやすい方法 — :F2(2小数)、:C(通貨)、:P(パーセント)、:X(16進)などのフォーマット指定子をサポート。String.Formatは位置プレースホルダ{0}、{1}とオプション配置({0,-10} = 左揃え、幅10)を使用。大きな文字列を構築するループにはStringBuilder(&ではなく)を使用し多くの中間文字列の作成を回避。Integer.Parseは無効入力でスロー;安全のためTryParseを使用。
Module IO
Sub Main()
' console output
Console.WriteLine("Hello, World!") ' with newline
Console.Write("No newline") ' without newline
Console.WriteLine() ' blank line
' string interpolation ($ before the string)
Dim name As String = "Alice"
Dim age As Integer = 30
Console.WriteLine($"Hello, {name}. You are {age} years old.")
Console.WriteLine($"Next year: {age + 1}") ' expressions work
Console.WriteLine($"Pi: {3.14159:F2}") ' format specifier
' String.Format (positional)
Dim msg As String = String.Format("{0} is {1} years old", name, age)
' composite formatting with alignment
Console.WriteLine("{0,-10} {1,5}", "Alice", 30) ' left/right align
Console.WriteLine("{0:C}", 1234.56) ' currency: $1,234.56
Console.WriteLine("{0:P}", 0.25) ' percent: 25.00 %
Console.WriteLine("{0:X}", 255) ' hex: FF
' console input
Console.Write("Enter name: ")
Dim input As String = Console.ReadLine()
Console.Write("Enter age: ")
Dim ageInput As Integer = Integer.Parse(Console.ReadLine())
' StringBuilder for efficient concatenation
Dim sb As New System.Text.StringBuilder()
For i As Integer = 1 To 100
sb.Append($"Line {i}").AppendLine()
Next
Console.WriteLine(sb.ToString())
End Sub
End Module制御フロー
If...Then...Elseと三項演算子
If...Then...ElseIf...ElseがVBの条件分岐。AndAlso/OrElseは短絡(不要なら右辺を評価しない) — 条件にはAnd/Orより常にこれらを推奨。If()関数(VB 14+)は三項演算子:If(condition, trueVal, falseVal)。2引数のIf()はnull合体演算子:If(maybeNull, defaultValue)。古いIIf()関数は避ける — 常に両分岐を評価しObjectを返す(ボクシング)。単一行IfはEnd If不要。