Shared Fields

Shared fields are useful to store information that is common to all instances of a class. For example, imagine you have a class named Document that represents a text document. You could implement a shared field acting as a counter of all the documents opened in your application:

Public Class Document    Private Shared _documentCounter As Integer    Public Sub New()    _documentCounter += 1    End SubEnd Class

The code in the example increments the counter each time a new instance is created. The documentCounter field is common to all instances of the Document class because it is marked with the Shared keyword.

Get Visual Basic 2015 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.