Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 36 ยท Classes and Objects

Classes, Objects and Properties

Learn object-oriented programming in Visual Basic .NET: declaring classes, fields, properties with validation, constructors (Sub New), Me, Shared members, access modifiers, With blocks and object initializers.

A class is a blueprint that bundles data (fields and properties) with behavior (methods). An object is one instance of a class created at run time. Object-oriented programming lets you model real things (a customer, an invoice, a button) and hide their internal details behind a clear public face. This lesson builds a class step by step in VB.NET (read-only listings) and mirrors each idea in a runnable C# stand-in using the same .NET object model.

A first class

VB
Public Class Product
    Public Name As String        ' a field
    Public Price As Decimal

    Public Sub PrintLabel()
        Console.WriteLine($"{Name}: {Price:C}")
    End Sub
End Class

Dim p As New Product()
p.Name = "Notebook"
p.Price = 4.5D
p.PrintLabel()

New Product() creates an object; the variable holds a reference to it. Members are reached with the dot. Public fields work, but they expose internals and cannot validate input. The idiomatic approach is private fields wrapped by public properties.

Properties

A property looks like a field to callers but runs code when read (Get) or written (Set):

VB
Public Class Product
    Private _price As Decimal

    Public Property Price As Decimal
        Get
            Return _price
        End Get
        Set(value As Decimal)
            If value < 0D Then
                Throw New ArgumentOutOfRangeException(NameOf(value), "Price cannot be negative.")
            End If
            _price = value
        End Set
    End Property
End Class

Inside Set, the special parameter value holds the assigned value. A property can be read-only (ReadOnly, only Get) or write-only (rare). When no extra logic is needed, use an auto-implemented property: the compiler creates the hidden field.

VB
Public Property Name As String                       ' read/write
Public ReadOnly Property Id As Integer               ' set only in the constructor
Public Property Stock As Integer = 10                ' with a default value
Public ReadOnly Property Total As Decimal            ' computed
    Get
        Return Price * Stock
    End Get
End Property

Computed properties like Total have no storage; they recalculate each time.

C# Stand-in (C#): property with validation and a computed property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Constructors: Sub New

A constructor runs when an object is created and puts it in a valid state. In VB it is a Sub named New. You can overload constructors and chain them with Me.New(...):

VB
Public Class Customer
    Public ReadOnly Property Id As Integer
    Public Property Name As String
    Public Property Email As String

    Public Sub New(id As Integer, name As String)
        Me.Id = id
        Me.Name = name
        Me.Email = ""
    End Sub

    Public Sub New(id As Integer, name As String, email As String)
        Me.New(id, name)           ' reuse the first constructor
        Me.Email = email
    End Sub
End Class

Dim c1 As New Customer(1, "Ada")
Dim c2 = New Customer(2, "Linus", "[email protected]")

Me is the current object (C#'s this). Use it to tell a parameter from a member with the same name. If you declare no constructor, the compiler supplies a parameterless one; as soon as you declare any, that default disappears.

Object initializers and With

An object initializer sets properties right after construction, without a custom constructor:

VB
Dim c3 As New Customer(3, "Grace") With {.Email = "[email protected]"}

The With statement lets you work on one object without repeating its name:

VB
With c3
    .Name = "Grace Hopper"
    .Email = "[email protected]"
End With

Shared members

A Shared member belongs to the class, not to any object. All instances see the same value, and you reach it through the class name.

VB
Public Class Counter
    Public Shared Count As Integer          ' one copy for the whole program

    Public Sub New()
        Count += 1
    End Sub

    Public Shared Function Describe() As String
        Return $"{Count} counters created"
    End Function
End Class

Dim a As New Counter()
Dim b As New Counter()
Console.WriteLine(Counter.Describe())       ' 2 counters created

A Shared constructor (Shared Sub New()) runs once before the first use and initializes shared data. Shared methods cannot touch instance members, because there is no Me.

C# Stand-in (C#): constructors, static members and object initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Access modifiers

Modifier Visible to
Public any code
Private the declaring class only (default for members)
Protected the class and its subclasses
Friend code in the same assembly (C#'s internal)
Protected Friend same assembly or subclasses
Private Protected subclasses in the same assembly

Class members default to Private, but types default to Friend. State the modifier explicitly so readers never wonder.

ToString, equality and garbage collection

Override ToString to give objects a readable text form; Console.WriteLine(obj) calls it. Compare references with Is; give a class value-like equality by overriding Equals and GetHashCode. You never free objects yourself: the garbage collector reclaims them when no references remain. Objects that hold unmanaged resources implement IDisposable and are wrapped in Using.

Design tips

  • Keep fields private; expose properties and methods.
  • Make invalid states impossible: validate in setters and constructors.
  • Prefer small classes with one clear responsibility.
  • Name classes with nouns (Invoice), methods with verbs (Pay), Boolean properties as questions (IsPaid).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the constructor of a VB.NET class called?

    Constructors are declared as Sub New and run when an object is created with New.
  2. 2. What does the keyword Me refer to?

    Me is the current instance, like this in C#.
  3. 3. What does a Shared field mean?

    Shared members belong to the class itself, not to any instance.
  4. 4. Why use a property with validation instead of a public field?

    Properties let the class control and validate access to its data.
  5. 5. How do you make a property that can only be set inside the constructor?

    A ReadOnly auto-property may be assigned only in a constructor or its initializer.

Summary

  • A class defines data and behavior; objects are instances created with New.
  • Prefer private fields with public properties (auto-implemented, validated or computed).
  • Constructors are Sub New; chain with Me.New; initialize with With { ... } or a With block.
  • Shared members belong to the class; Me is the current instance.
  • Choose access modifiers deliberately (Public, Private, Protected, Friend).

Next: Inheritance and Interfaces