The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
VB
1
Print a literal string on standard output
System.Console.WriteLine("Hello World!")
2
Loop to execute some code a constant number of times
For x = 1 To 10
    Console.WriteLine("Hello")
Next x
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
Sub Finish(name As String)
    Console.WriteLine($"My job here is done. Goodbye {name}")
End Sub
4
Create a function which returns the square of an integer
Function Square(x As Integer) As Double
    Return x ^ 2
End Function
Alternative implementation:
Function Square(x As Integer) As Integer
    Return x * x
End Function
5
Declare a container type for two floating-point numbers x and y
Structure Point
    Public x As Double
    Public y As Double
End Structure
6
Do something with each item x of the list (or array) items, regardless indexes.
For Each x In items
    DoSomething(x)
Next
7
Print each index i with its value x from an array-like collection items
For i As Integer = 0 To items.Count - 1
    Dim x = items(i)
    Console.WriteLine($"Item {i} = {x}")
Next
Alternative implementation:
For i As Integer = 0 To items.Length - 1
    Dim x = items(i)
    Console.WriteLine($"Item {i} = {x}")
Next
Alternative implementation:
For i = LBound(items) To UBound(items)
    x = items(i)
    Debug.Print i & ": " & x
Next
8
Create a new map object x, and provide some (key, value) pairs as initial content.
Dim x As New Dictionary(Of String, Integer)() From {
    {"one", 1},
    {"two", 2}
}
10
Generate a random permutation of the elements of list x
Function Shuffle(Of T)(collection As IEnumerable(Of T)) As List(Of T)
    Dim r As Random = New Random()
    Shuffle = collection.OrderBy(Function(a) r.Next()).ToList()
End Function
11
The list x must be non-empty.
x(Random.Shared.Next(x.Count))
Alternative implementation:
x(New Random().Next(x.Count))
12
Check if the list contains the value x.
list is an iterable finite container.
List.Contains(x)
14
Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.
Function pick(a As Double, b As Double) As Double
    Static rng As New Random()
    Return rng.NextDouble() * (b - a) + a
End Function
19
Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.
Dim ItemList As New List(Of String)(New String() {"one", "two", "three"})
ItemList.Reverse()
For Each item In ItemList
    Console.WriteLine(item)
Next
21
Swap the values of the variables a and b
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
  Dim tmp as T
  tmp = a
  a = b
  b = tmp 
End Sub
22
Extract the integer value i from its string representation s (in radix 10)
Dim myint As Integer = CInt(("123"))
24
Declare a new string s and initialize it with the literal value "ネコ" (which means "cat" in japanese)
Dim s As String = "ネコ"
26
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
Dim x(m - 1, n - 1) As Double
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
items.OrderBy(Function(x) x.p)
Alternative implementation:
System.Array.Sort(items, Comparer(Of Item).Create(Function(a, b) a.p - b.p))
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
Function f(i As Integer) As Integer
    Return If(i = 0, 1, i * f(i - 1))
End Function
35
Implement a function compose (A -> C) with parameters f (A -> B) and g (B -> C), which returns the composition function g ∘ f
Function compose(f As Func(Of A, B), g As Func(Of B, C)) As Func(Of A, C)
    Return Function(a) g(f(a))
End Function
36
Implement a function compose which returns composition function g ∘ f for any functions f and g having exactly 1 parameter.
Function Compose(Of T1, T2, T3)(f As Func(Of T1, T2), g As Func(Of T2, T3)) As Func(Of T1, T3)
    Return Function(x) g(f(x))
End Function
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
Dim t As String = s.Substring(i,j)
39
Set the boolean ok to true if the string word is contained in string s as a substring, or to false otherwise.
Dim ok As Boolean = s.Contains(word)
41
Create the string t containing the same characters as the string s, in reverse order.
The original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
Dim string_t = StrReverse(string_s)
43
Look for a negative value v in 2D integer matrix m. Print it and stop searching.
For i As Integer = 0 To m.GetLength(0) - 1
    For j As Integer = 0 To m.GetLength(1) - 1
        If m(i, j) < 0 Then
            Console.WriteLine(m(i, j))
            i = Integer.MaxValue - 1 ' Break outer loop.
            Exit For
        End If
    Next
Next
Alternative implementation:
    For Each row As Integer() in m
        For Each v As Integer In row
            If v < 0 Then
                Console.WriteLine(v)
                GoTo DONE
            End If
        Next
    Next
DONE:
Alternative implementation:
Dim colCount As Integer = m(0).Length
For Each row As Integer() In m
    Dim j = 0
    Do While j < colCount
        Dim v = row(j)
        If v < 0 Then
            Console.WriteLine(v)
            Exit For
        End If
        j += 1
    Loop
Next
Alternative implementation:
Select Case Nothing
    Case Else
        For Each row As Integer() in m
            For Each v As Integer In row
                If v < 0 Then
                    Console.WriteLine(v)
                    Exit Select
                End If
            Next
        Next
End Select
44
Insert the element x at position i in the list s. Further elements must be shifted to the right.
s.Insert(i,x)
45
Sleep for 5 seconds in current thread, before proceeding with the next instructions.
System.Threading.Thread.Sleep(5000)
47
Create string t consisting in the 5 last characters of string s.
Make sure that multibyte characters are properly handled.
t = s.Substring(s.Length - 5)
Alternative implementation:
t = Right(s, 5)
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
Dim s as String = "
This
Is
Multiline
Text!"
50
Write a loop that has no end clause.
Do
    ' Do something
Loop
51
Determine whether the map m contains an entry for the key k
If m.ContainsKey(k) Then...
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
Dim x = {"a", "b", "c", "d"}.ToList
Dim y = String.Join(",", x)
54
Calculate the sum s of the integer list or array x.
Dim s As Integer = x.Sum()
55
Create the string representation s (in radix 10) of the integer value i.
Dim myInt As Integer = 12345
Console.WriteLine(myInt.ToString)
58
Create the string lines from the content of the file with filename f.
Dim lines = IO.File.ReadAllText(f)
61
Assign to the variable d the current date/time value, in the most standard type.
Dim d As DateTime = DateTime.Now()
63
Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.
Dim x2 As String = x.Replace(y, z, StringComparison.Ordinal)
74
Compute the greatest common divisor x of big integers a and b. Use an integer type able to handle huge numbers.
Dim x = BigInteger.GreatestCommonDivisor(a, b)	
78
Execute a block once, then execute it again as long as boolean condition c is true.
Do 
    SomeThing()
    SomeOtherThing()
Loop While c
87
Exit immediately.
If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.
End()
96
Set the boolean b to true if string s starts with prefix prefix, false otherwise.
Dim b As Boolean = s.StartsWith(prefix)
99
Assign to the string x the value of the fields (year, month, day) of the date d, in format YYYY-MM-DD.
Dim x As String = d.ToString("yyyy-MM-dd")
110
Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise.
Dim blank As Boolean = String.IsNullOrWhitespace(s)
116
Remove all occurrences of string w from string s1, and store the result in s2.
Dim s2 As String = s1.Replace(w, String.Empty)
117
Set n to the number of elements of the list x.
Dim n As Integer = x.Count
Alternative implementation:
n = UBound(x) + 1
119
Remove duplicates from the list x.
Explain if the original order is preserved.
x = x.Distinct.ToList
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
Enum Suit
    Spades
    Hearts
    Diamonds
    Clubs
End Enum
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
If c1 Then
    f1()
ElseIf c2 Then
    f2()
else c3 Then
    f3()
End If
134
Declare and initialize a new list items, containing 3 elements a, b, c.
Dim salmons As New List(Of String) From
    {"chinook", "coho", "pink", "sockeye"}
137
Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.
Dim x As String = "123456"
Dim b As Boolean = IsNumeric(x)
145
Print message msg, prepended by current date and time.

Explain what behavior is idiomatic: to stdout or stderr, and what the date format is.
My.Application.Log.WriteEntry(msg,TraceEventType.Verbose)
157
Initialize a constant planet with string value "Earth".
Const PLANET = "Earth"
163
Print all the list elements, two by two, assuming list length is even.
Dim ItemList As New List(Of String)(New String() {"one", "one", "two", "two", "three", "three"})
For x = 0 To ItemList.Count - 1 Step 2
    Console.WriteLine(ItemList(x) & vbTab & ItemList(x + 1))
Next
165
Assign to the variable x the last element of the list items.
Dim x = items(items.Count - 1)
169
Assign to the integer n the number of characters of the string s.
Make sure that multibyte characters are properly handled.
n can be different from the number of bytes of s.
Dim n As Integer = s.Length
171
Append the element x to the list s.
s.Add(x)
184
Assign to variable t a string representing the day, month and year of the day after the current date.
Dim t As Date = Date.Today.AddDays(1)
196
Given an integer array a of size n, pass the first, third, fifth and seventh, ... up to the m th element to a routine foo which sets all these elements to 42.
Sub Foo(ByRef element As Integer)
    element = 42
End Sub

' Statements in caller:
For i = 0 To m - 1 Step 2
    Foo(a(i))
Next
197
Retrieve the contents of file at path into a list of strings lines, in which each element is a line of the file.
Dim lines = IO.File.ReadAllLines(path).ToList
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
Dim _foo as String
Try
	foo = Environment.GetEnvironmentVariable("FOO")
Catch ex as Exception
	foo = "none"
End Try
Alternative implementation:
foo = IIf(Environ("FOO") = "", "none", Environ("FOO"))
206
Execute different procedures foo, bar, baz and barfl if the string str contains the name of the respective procedure. Do it in a way natural to the language.
CallByName(receiver, str, CallType.Method)
Alternative implementation:
Select Case str
    Case NameOf(Foo)
        Foo()
    Case NameOf(Bar)
        Bar()
    Case NameOf(Baz)
        Baz()
    Case NameOf(Barfl)
        Barfl()
End Select
219
Create the string t from the value of string s with each sequence of spaces replaced by a single space.

Explain if only the space characters will be replaced, or the other whitespaces as well: tabs, newlines.
Dim t As String = Regex.Replace(s, " +", " ")
Alternative implementation:
Dim t As String = Regex.Replace(s, "\s+", " ")
220
Create t consisting of 3 values having different types.

Explain if the elements of t are strongly typed or not.
Dim t = (2.5F, "foo", True)
224
Insert the element x at the beginning of the list items.
items.Insert(0, x)
Alternative implementation:
items = items.Prepend(x).ToList()
225
Declare an optional integer argument x to procedure f, printing out "Present" and its value if it is present, "Not present" otherwise
Sub f(Optional x As Integer? = Nothing)
    Console.WriteLine(If(x.HasValue, $"Present {x}", "Not Present"))
End Sub
234
Assign to the string s the standard base64 encoding of the byte array data, as specified by RFC 4648.
Dim s As String = Convert.ToBase64String(data)
235
Assign to byte array data the bytes represented by the base64 string s, as specified by RFC 4648.
Dim bytes As Byte() = Convert.FromBase64String(s)
237
Assign to c the result of (a xor b)
Dim c As Integer = a Xor b
245
Print the value of object x having custom type T, for log or debug.
Debug.Print x
256
Print the numbers 5, 4, ..., 0 (included), one line per number.
For i = 5 To 0 Step -1
    Console.WriteLine(i)
Next
258
Convert the string values from list a into a list of integers b.
For i = LBound(a) To UBound(a)
    b(i) = CInt(a(i))
Next
268
Define a type vector containing three floating point numbers x, y, and z. Write a user-defined operator x that calculates the cross product of two vectors a and b.
Structure Vector
    Public X, Y, Z As Double

    Shared Operator *(a As Vector, b As Vector) As Vector
        Return New Vector() With {
            .X = a.Y*b.Z - a.Z*b.Y,
            .Y = a.Z*b.X - a.X*b.Z,
            .Z = a.X*b.Y - a.Y*b.X
        }
    End Operator
End Structure
289
Create the string s by concatenating the strings a and b.
s = a & b
299
Write a line of comments.

This line will not be compiled or executed.
Rem this is a comment line