Creating Classes

Using objects is fairly straightforward and intuitive. It is the kind of thing that even the most novice programmers pick up and accept rapidly.

Basic Classes

As discussed earlier, objects are merely instances of a specific template (a class). The class contains the code that defines the behavior of its objects, and defines the instance variables that will contain the object's individual data.

Classes are created using the Class keyword, and include definitions (declaration) and implementations (code) for the variables, methods, properties, and events that make up the class. Each object created based on this class will have the same methods, properties, and events, and its own set of data defined by the fields in the class.

The Class Keyword

If you want to create a class that represents a person — a Person class — you could use the Class keyword:

Public Class Person
   ' Implementation code goes here
End Class

As you know, Visual Basic projects are composed of a set of files with the .vb extension. It is possible for each file to contain multiple classes, which means that within a single file you could have something like this:

Public Class Adult
  ' Implementation code goes here.
End Class
        
Public Class Senior
  ' Implementation code goes here.
End Class
        
Public Class Child
  ' Implementation code goes here.
End Class

The most common and preferred approach is to have a single class per file. This is because the Visual Studio 2012 Solution Explorer and the code-editing ...

Get Professional Visual Basic 2012 and .NET 4.5 Programming 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.