Skip to content
AgileLogics
6 min read

Namespaces, Projects, and NuGet

Prerequisites: Classes and objects

Namespaces

A namespace groups related types and prevents name clashes. .NET's own types live in namespaces like System.IO and System.Collections.Generic.

Namespace Shop.Billing
    Public Class Invoice
        Public Property Total As Decimal
    End Class
End Namespace

Namespace Shop.Shipping
    Public Class Invoice
        Public Property Carrier As String
    End Class
End Namespace

Module Program
    Sub Main()
        Dim bill As New Shop.Billing.Invoice With {.Total = 42D}
        Dim label As New Shop.Shipping.Invoice With {.Carrier = "PostCo"}
        Console.WriteLine($"{bill.Total} {label.Carrier}")
        Console.WriteLine(bill.GetType().FullName)
    End Sub
End Module
42 PostCo
Demo.Shop.Billing.Invoice

Two classes named Invoice coexist because they're in different namespaces. Notice the full name starts with Demo. — VB projects have a root namespace (set in the project file, Demo here) that is added in front of every namespace you declare.

Imports

Imports System.Text
Imports IO = System.IO

Module Program
    Sub Main()
        Dim sb As New StringBuilder()
        sb.Append("file ").Append("name: ")
        sb.Append(IO.Path.GetFileName("data/file.txt"))
        Console.WriteLine(sb.ToString())
    End Sub
End Module
file name: file.txt

Imports goes at the top of a file; Imports IO = System.IO creates an alias. Project-wide imports are listed in the .vbproj (the templates already import System, System.Linq, and others).

Solutions and projects

dotnet new sln -n Shop
dotnet new classlib -lang VB -o src/Shop.Core
dotnet new console -lang VB -o src/Shop.Cli
dotnet new mstest -lang VB -o tests/Shop.Tests
dotnet sln add src/Shop.Core src/Shop.Cli tests/Shop.Tests
dotnet add src/Shop.Cli reference src/Shop.Core
dotnet add tests/Shop.Tests reference src/Shop.Core

A class library (.dll) holds business logic; the console or Windows app and the test project reference it. Unlike F#, the order of .vb files doesn't matter — the compiler sees the whole project at once.

NuGet packages

dotnet add package Newtonsoft.Json
dotnet add package Microsoft.Data.Sqlite
dotnet list package

This adds a <PackageReference> to the .vbproj:

<ItemGroup>
  <PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.0" />
</ItemGroup>

Nearly every .NET library on nuget.org works from Visual Basic, because they're compiled to the same IL — even though their documentation shows C# examples. In Visual Studio, Manage NuGet Packages does the same thing with a GUI.

What's next

Try the Intermediate Projects, then continue to Level 3 — Advanced: async programming, Windows Forms, data, VBA, migration from VB6, and shipping Visual Basic applications.