Lessons in this course (12)

5. Arrays, generics and collections

Basic★ Must knowLesson 5 of 12
vb
Dim marks(4) As Integer                  ' 5 elements! VB declares the UPPER BOUND (0..4), C# declares the length
Dim primes() As Integer = {2, 3, 5, 7}
Dim grid(1, 2) As Integer                ' 2 x 3 multidimensional
ReDim Preserve marks(9)                  ' resize keeping values (creates a new array)
Console.WriteLine(primes.Length)

Dim names As New List(Of String) From {"Asha", "Ravi"}     ' generics use (Of T)
names.Add("Meera")
Dim stock As New Dictionary(Of String, Integer) From {{"pen", 10}, {"book", 4}}
Dim qty As Integer
If stock.TryGetValue("pen", qty) Then Console.WriteLine(qty)

Dim adults = people.Where(Function(p) p.Age >= 18).OrderBy(Function(p) p.Name).ToList()

' Generic class and method with constraint
Public Class Repository(Of T As {Class, New})
    Private ReadOnly _items As New List(Of T)
    Public Function Create() As T
        Dim item As New T()
        _items.Add(item)
        Return item
    End Function
End Class

Indexing uses parentheses arr(0), not square brackets — the same syntax as method calls.