44
Object-Oriented Programming using Visual Basic All managed languages in the .NET Framework, such as Visual Basic and C#, provide full support for object-oriented programming including encapsulation, inheritance, and polymorphism. Encapsulation means that a group of related properties, methods, and other members are treated as a single unit or object. Inheritance describes the ability to create new classes based on an existing class. Polymorphism means that you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways. Classes and Objects The terms class and object are sometimes used interchangeably, but in fact, classes describe the type of objects, while objects are usable instances of classes. So, the act of creating an object is called instantiation. Using the blueprint analogy, a class is a blueprint, and an object is a building made from that blueprint. To define a class: Class SampleClass End Class Both Visual Basic and C# also provide a light version of classes called structures that are useful when you need to create large array of objects and do not want to consume too much memory for that. To define a structure: Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Classes and Objects in VB2010

Embed Size (px)

DESCRIPTION

Classes and Objects in VB2010

Citation preview

Page 1: Classes and Objects in VB2010

Object-Oriented Programming using Visual Basic

All managed languages in the .NET Framework, such as Visual Basic and C#, provide full support for object-oriented programming including encapsulation, inheritance, and polymorphism.

Encapsulation means that a group of related properties, methods, and other members are treated as a single unit or object.

Inheritance describes the ability to create new classes based on an existing class.

Polymorphism means that you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.

Classes and Objects

The terms class and object are sometimes used interchangeably, but in fact, classes describe the type of objects, while objects are usable instances of classes. So, the act of creating an object is called instantiation. Using the blueprint analogy, a class is a blueprint, and an object is a building made from that blueprint.

To define a class:

Class SampleClassEnd Class

Both Visual Basic and C# also provide a light version of classes called structures that are useful when you need to create large array of objects and do not want to consume too much memory for that.

To define a structure:

Structure SampleStructureEnd Structure

Class Members

Each class can have different class members that include properties that describe class data, methods that define class behavior, and events that provide communication between different classes and objects.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 2: Classes and Objects in VB2010

Properties and Fields

Fields and properties represent information that an object contains. Fields are like variables because they can be read or set directly.

To define a field:

Class SampleClass Public SampleField As StringEnd Class

Properties have get and set procedures, which provide more control on how values are set or returned.

Both C# and Visual Basic allow you either to create a private field for storing the property value or use so-called auto-implemented properties that create this field automatically behind the scenes and provide the basic logic for the property procedures.

To define an auto-implemented property:

Class SampleClass Public Property SampleProperty as StringEnd Class

If you need to perform some additional operations for reading and writing the property value, define a field for storing the property value and provide the basic logic for storing and retrieving it:

Class Samplelass Private m_Sample As String Public Property Sample() As String Get ' Return the value stored in the field. Return m_Sample End Get Set(ByVal Value As String) ' Store the value in the field. m_Sample = Value End Set End PropertyEnd Class

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 3: Classes and Objects in VB2010

Most properties have methods or procedures to both set and get the property value. However, you can create read-only or write-only properties to restrict them from being modified or read. In Visual Basic you can use ReadOnly and WriteOnly keywords. In C#, you can omit the get or set property method. However, in both Visual Basic and C#, auto-implemented properties cannot be read-only or write-only.

For more information, see:

Visual Basico Property Statement o Get Statement o Set Statement (Visual Basic) o ReadOnly (Visual Basic) o WriteOnly (Visual Basic)

Methods

A method is an action that an object can perform.

NoteIn Visual Basic, there are two ways to create a method: the Sub statement is used if the method does not return a value; the Function statement is used if a method returns a value.

To define a method of a class:

Class SampleClass Public Function SampleFunc(ByVal SampleParam As String) ' Add code here End FunctionEnd Class

A class can have several implementations, or overloads, of the same method that differ in the number of parameters or parameter types.

To overload a method:

Overloads Sub Display(ByVal theChar As Char) ' Add code that displays Char data.End SubOverloads Sub Display(ByVal theInteger As Integer) ' Add code that displays Integer data.End Sub

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 4: Classes and Objects in VB2010

In most cases you declare a method within a class definition. However, both Visual Basic and C# also support extension methods that allow you to add methods to an existing class outside the actual definition of the class.

For more information, see:

Visual Basico Function Statement (Visual Basic) o Sub Statement (Visual Basic) o Overloads (Visual Basic) o Extension Methods (Visual Basic)

Constructors

Constructors are class methods that are executed automatically when an object of a given type is created. Constructors usually initialize the data members of the new object. A constructor can run only once when a class is created. Furthermore, the code in the constructor always runs before any other code in a class. However, you can create multiple constructor overloads in the same way as for any other method.

To define a constructor for a class:

Class SampleClass Sub New(ByVal s As String) // Add code here. End SubEnd Class

For more information, see:

Visual Basico Sub Newo Object Lifetime: How Objects Are Created and Destroyed (Visual Basic)

Destructors

Destructors are used to destruct instances of classes. In the .NET Framework, the garbage collector automatically manages the allocation and release of memory for the managed objects in your application. However, you may still need destructors to clean up any unmanaged resources that your application creates. There can be only one destructor for a class.

For more information about destructors and garbage collection in the .NET Framework, see Garbage Collection.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 5: Classes and Objects in VB2010

Events

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. For more information about events, how they are raised and handled, see Handling and Raising Events.

Visual Basico To declare events, use the Event Statement.o To raise events, use the RaiseEvent Statement.o To specify event handlers using a declarative way, use the WithEvents (Visual

Basic) statement and the Handles Clause (Visual Basic) clause.o To be able to dynamically add, remove, and change the event handler associated

with an event, use the AddHandler Statement and RemoveHandler Statement together with the AddressOf Operator (Visual Basic).

Nested Classes

A class defined within another class is called nested. By default, the nested class is private.

Class Container Class Nested ' Add code here. End ClassEnd Class

To create an instance of the nested class, use the name of the container class followed by the dot and then followed by the name of the nested class:

Dim nestedInstance As Container.Nested = New Container.Nested()

Access Modifiers and Access Levels

All classes and class members can specify what access level they provide to other classes by using access modifiers.

The following access modifiers are available:

Visual Basic Modifier Definition

Public (Visual Basic) The type or member can be accessed by any other code in the same assembly or another assembly that references it.

Private (Visual Basic) The type or member can only be accessed by code in the same

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 6: Classes and Objects in VB2010

class.

Protected (Visual Basic) The type or member can only be accessed by code in the same class or in a derived class.

Friend (Visual Basic) The type or member can be accessed by any code in the same assembly, but not from another assembly.

Protected Friend The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

Instantiating Classes

To create an object, you need to instantiate a class, or create a class instance.

Dim sampleObject as New SampleClass()

After instantiating a class, you can assign values to the instance's properties and fields and invoke class methods.

' Set a property value.sampleObject.SampleProperty = "Sample String"' Call a method.sampleObject.SampleMethod()

To assign values to properties during the class instantiation process, use object initializers:

Dim sampleObject = New SampleClass With {.FirstProperty = "A", .SecondProperty = "B"}

For more information, see:

Visual Basico New Operator (Visual Basic) o Object Initializers: Named and Anonymous Types (Visual Basic)

C#o new Operator (C# Reference) o Object and Collection Initializers (C# Programming Guide)

Static (Shared) Classes and Members

A static (shared in Visual Basic) member of the class is a property, procedure, or field that is shared by all instances of a class.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 7: Classes and Objects in VB2010

To define a static (shared) member:

Class SampleClass Public Shared SampleString As String = "Sample String"End Class

To access the static (shared) member, use the name of the class without creating an object of this class:

MsgBox(SampleClass.SampleString)

Static (shared) classes in C# and modules in Visual Basic have static (shared) members only and cannot be instantiated. Static (shared) members also cannot access non-static (non-shared) properties, fields or methods

For more information, see:

Visual Basico Shared (Visual Basic) o Module Statement

Anonymous Types

Anonymous types enable you to create objects without writing a class definition for the data type. Instead, the compiler generates a class for you. The class has no usable name and contains the properties you specify in declaring the object.

To create an instance of an anonymous type:

' sampleObject is an instance of a simple anonymous type.Dim sampleObject = New With {Key .FirstProperty = "A", .SecondProperty = "B"}

For more information, see:

Visual Basic: Anonymous Types (Visual Basic) C#: Anonymous Types (C# Programming Guide)

Inheritance

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 8: Classes and Objects in VB2010

Inheritance enables you to create a new class that reuses, extends, and modifies the behavior that is defined in another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. However, all classes in both C# and Visual Basic implicitly inherit from the Object class that supports .NET class hierarchy and provides low-level services to all classes.

NoteManaged languages in the .NET Framework do not support multiple inheritance, i.e. you can specify only one base class for a derived class.

To inherit from a base class:

Class DerivedClass Inherits BaseClassEnd Class

By default all classes can be inherited. However, you can specify whether a class must not be used as a base class, or create a class that can be used as a base class only.

To specify that a class cannot be used as a base class:

NotInheritable Class SampleClassEnd Class

To specify that a class can be used as a base class only and cannot be instantiated:

MustInherit Class BaseClassEnd Class

For more information, see:

Visual Basico Inherits Statement o NotInheritable (Visual Basic) o MustInherit (Visual Basic)

Overriding Members

By default, a derived class inherits all members from its base class. If you want to change the behavior of the inherited member, you need to override it. That is, you can define a new implementation of the method, property or event in the derived class.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 9: Classes and Objects in VB2010

The following modifiers are used to control how properties and methods are overridden:

Visual Basic Modifier DefinitionOverridable (Visual Basic) Allows a class member to be overridden in a derived class.

Overrides (Visual Basic) Overrides a virtual (overridable) member defined in the base class.

NotOverridable (Visual Basic) Prevents a member from being overridden in an inheriting class.

MustOverride (Visual Basic) Requires that a class member to be overridden in the derived class.

Shadows (Visual Basic) Hides a member inherited from a base classInterfaces

Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. An interface represents a contract, in that a class that implements an interface must implement every aspect of that interface exactly as it is defined.

To define an interface:

Public Interface ISampleInterface Sub DoSomething()End Interface

To implement an interface in a class:

Class SampleClass Implements ISampleInterface Sub doSomething ' Method implementation. End SubEnd Class

For more information, see:

Visual Basico Interfaces (Visual Basic) o Interface Statement (Visual Basic) o Implements Statement

Generics

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 10: Classes and Objects in VB2010

Classes, structures, interfaces and methods in the .NET Framework can type parameters that define types of objects that they can store or use. The most common example of generics is a collection, where you can specify the type of objects to be stored in a collection.

To define a generic class:

Class SampleGeneric(Of T) Public Field As TEnd Class

To create an instance of a generic class:

Dim sampleObject As New SampleGeneric(Of String)sampleObject.Field = "Sample string"Delegates

A delegate is a type that defines a method signature, and can provide a reference to any method with a compatible signature. You can invoke (or call) the method through the delegate. Delegates are used to pass methods as arguments to other methods.

NoteEvent handlers are nothing more than methods that are invoked through delegates. For more information about using delegates in event handling, see Events and Delegates.

To create a delegate:

Delegate Sub SampleDelegate(ByVal str As String)

To create a reference to a method that matches the signature specified by the delegate:

Class SampleClass ' Method that matches the SampleDelegate signature. Sub SampleSub(ByVal str As String) ' Add code here. End Sub ' Method that instantiates the delegate. Sub SampleDelegateSub() Dim sd As SampleDelegate = AddressOf SampleSub sd("Sample string") End Sub

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 11: Classes and Objects in VB2010

End Class

For more information, see:

Visual Basico Delegates (Visual Basic) o Delegate Statement o AddressOf Operator (Visual Basic)

Defining Classes

This walkthrough demonstrates how to define classes, which you can then use to create objects. It also shows you how to add properties and methods to the new class, and demonstrates how to initialize an object.

NoteYour computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To define a class

1. Create a project by clicking New Project on the File menu. The New Project dialog box appears.

2. Select Windows Application from the list of Visual Basic project templates to display the new project.

3. Add a new class to the project by clicking Add Class on the Project menu. The Add New Item dialog box appears.

4. Select the Class template.5. Name the new class UserNameInfo.vb, and then click Add to display the code for the

new class.

Public Class UserNameInfoEnd Class

NoteYou can use the Visual Basic Code Editor to add a class to your startup form by typing the

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 12: Classes and Objects in VB2010

Class keyword followed by the name of the new class. The Code Editor provides a corresponding End Class statement for you.

6. Define a private field for the class by adding the following code between the Class and End Class statements:

Private userNameValue As String

Declaring the field as Private means it can be used only within the class. You can make fields available from outside a class by using access modifiers such as Public that provide more access. For more information, see Access Levels in Visual Basic.

7. Define a property for the class by adding the following code:

Public Property UserName() As String Get ' Gets the property value. Return userNameValue End Get Set(ByVal Value As String) ' Sets the property value. userNameValue = Value End SetEnd Property

8. Define a method for the class by adding the following code:

Public Sub Capitalize() ' Capitalize the value of the property. userNameValue = UCase(userNameValue)End Sub

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 13: Classes and Objects in VB2010

9. Define a parameterized constructor for the new class by adding a procedure named Sub New:

Public Sub New(ByVal UserName As String) ' Set the property value. Me.UserName = UserNameEnd Sub

The Sub New constructor is called automatically when an object based on this class is created. This constructor sets the value of the field that holds the user name.

To create a button to test the class

1. Change the startup form to design mode by right-clicking its name in Solution Explorer and then clicking View Designer. By default, the startup form for Windows Application projects is named Form1.vb. The main form will then appear.

2. Add a button to the main form and double-click it to display the code for the Button1_Click event handler. Add the following code to call the test procedure:

' Create an instance of the class.Dim user As New UserNameInfo("Moore, Bobby")' Capitalize the value of the property.user.Capitalize()' Display the value of the property.MsgBox("The original UserName is: " & user.UserName)' Change the value of the property.user.UserName = "Worden, Joe"' Redisplay the value of the property.MsgBox("The new UserName is: " & user.UserName)

To run your application

1. Run your application by pressing F5. Click the button on the form to call the test procedure. It displays a message stating that the original UserName is "MOORE, BOBBY", because the procedure called the Capitalize method of the object.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 14: Classes and Objects in VB2010

2. Click OK to dismiss the message box. The Button1 Click procedure changes the value of the UserName property and displays a message stating that the new value of UserName is "Worden, Joe".

Objects and Classes in Visual Basic

An object is a combination of code and data that can be treated as a unit. An object can be a piece of an application, like a control or a form. An entire application can also be an object.

When you create an application in Visual Basic, you constantly work with objects. You can use objects provided by Visual Basic, such as controls, forms, and data access objects. You can also use objects from other applications within your Visual Basic application. You can even create your own objects and define additional properties and methods for them. Objects act like prefabricated building blocks for programs — they let you write a piece of code once and reuse it over and over.

This topic discusses objects in detail.

Objects and Classes

Each object in Visual Basic is defined by a class. A class describes the variables, properties, procedures, and events of an object. Objects are instances of classes; you can create as many objects you need once you have defined a class.

To understand the relationship between an object and its class, think of cookie cutters and cookies. The cookie cutter is the class. It defines the characteristics of each cookie, for example size and shape. The class is used to create objects. The objects are the cookies.

You must create an object before you can access its members.

To create an object from a class

1. Determine from which class you want to create an object.2. Write a Dim Statement (Visual Basic) to create a variable to which you can assign a class

instance. The variable should be of the type of the desired class.3. Dim nextCustomer As customer 4. Add the New Operator (Visual Basic) keyword to initialize the variable to a new instance

of the class.5. Dim nextCustomer As New customer6. You can now access the members of the class through the object variable.7. nextCustomer.accountNumber = lastAccountNumber + 1

NoteWhenever possible, you should declare the variable to be of the class type you intend to assign to it. This is called early binding. If you do not know the class type at compile time, you can

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 15: Classes and Objects in VB2010

invoke late binding by declaring the variable to be of the Object Data Type. However, late binding can make performance slower and limit access to the run-time object's members. For more information, see Object Variable Declaration (Visual Basic).

Multiple Instances

Objects newly created from a class are often identical to each other. Once they exist as individual objects, however, their variables and properties can be changed independently of the other instances. For example, if you add three check boxes to a form, each check box object is an instance of the CheckBox class. The individual CheckBox objects share a common set of characteristics and capabilities (properties, variables, procedures, and events) defined by the class. However, each has its own name, can be separately enabled and disabled, and can be placed in a different location on the form.

Object Members

An object is an element of an application, representing an instance of a class. Fields, properties, methods, and events are the building blocks of objects and constitute their members.

Member Access

You access a member of an object by specifying, in order, the name of the object variable, a period (.), and the name of the member. The following example sets the Text property of a Label object.

warningLabel.Text = "Data not saved"

IntelliSense Listing of Members

IntelliSense lists members of a class when you invoke its List Members option, for example when you type a period (.) as a member-access operator. If you type the period following the name of a variable declared as an instance of that class, IntelliSense lists all the instance members and none of the shared members. If you type the period following the class name itself, IntelliSense lists all the shared members and none of the instance members. For more information, see Using IntelliSense.

Fields and Properties

Fields and properties represent information stored in an object. You retrieve and set their values with assignment statements the same way you retrieve and set local variables in a procedure. The following example retrieves the Width property and sets the ForeColor property of a Label object.

Dim warningWidth As Integer = warningLabel.Width

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 16: Classes and Objects in VB2010

warningLabel.ForeColor = System.Drawing.Color.Red

Note that a field is also called a member variable.

Use property procedures when:

You need to control when and how a value is set or retrieved. The property has a well-defined set of values that need to be validated. Setting the value causes some perceptible change in the object's state, such as an

IsVisible property. Setting the property causes changes to other internal variables or to the values of other

properties. A set of steps must be performed before the property can be set or retrieved.

Use fields when:

The value is of a self-validating type. For example, an error or automatic data conversion occurs if a value other than True or False is assigned to a Boolean variable.

Any value in the range supported by the data type is valid. This is true of many properties of type Single or Double.

The property is a String data type, and there is no constraint on the size or value of the string.

For more information, see Property Procedures (Visual Basic).

Methods

A method is an action that an object can perform. For example, Add is a method of the ComboBox object that adds a new entry to a combo box.

The following example demonstrates the Start method of a Timer object.

Dim safetyTimer As New System.Windows.Forms.TimersafetyTimer.Start()

Note that a method is simply a procedure that is exposed by an object.

For more information, see Procedures in Visual Basic.

Events

An event is an action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code to respond. Events can occur as a result of a user action or program code, or they can be caused by the system. Code that signals an event is said to raise the event, and code that responds to it is said to handle it.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 17: Classes and Objects in VB2010

You can also develop your own custom events to be raised by your objects and handled by other objects. For more information, see Events (Visual Basic).

Instance Members and Shared Members

When you create an object from a class, the result is an instance of that class. Members that are not declared with the Shared (Visual Basic) keyword are instance members, which belong strictly to that particular instance. An instance member in one instance is independent of the same member in another instance of the same class. An instance member variable, for example, can have different values in different instances.

Members declared with the Shared keyword are shared members, which belong to the class as a whole and not to any particular instance. A shared member exists only once, no matter how many instances of its class you create, or even if you create no instances. A shared member variable, for example, has only one value, which is available to all code that can access the class.

Accessing Nonshared Members

To access a nonshared member of an object

1. Make sure the object has been created from its class and assigned to an object variable.2. Dim secondForm As New System.Windows.Forms.Form3. In the statement that accesses the member, follow the object variable name with the

member-access operator (.) and then the member name.4. secondForm.Show()

Accessing Shared Members

To access a shared member of an object

Follow the class name with the member-access operator (.) and then the member name. You should always access a Shared member of the object directly through the class name.

MsgBox("This computer is called " & Environment.MachineName) If you have already created an object from the class, you can alternatively access a

Shared member through the object's variable.

Differences Between Classes and Modules

The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot. Because there is only one copy of a standard module's data, when one part of your program changes a public variable in a standard module, any other part of the program gets the same value if it then reads that variable. In contrast, object data exists

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 18: Classes and Objects in VB2010

separately for each instantiated object. Another difference is that unlike standard modules, classes can implement interfaces.

NoteWhen the Shared modifier is applied to a class member, it is associated with the class itself instead of a particular instance of the class. The member is accessed directly by using the class name, the same way module members are accessed.

Classes and modules also use different scopes for their members. Members defined within a class are scoped within a specific instance of the class and exist only for the lifetime of the object. To access class members from outside a class, you must use fully qualified names in the format of Object.Member.

On the other hand, members declared within a module are publicly accessible by default, and can be accessed by any code that can access the module. This means that variables in a standard module are effectively global variables because they are visible from anywhere in your project, and they exist for the life of the program.

Reusing Classes and Objects

Objects let you declare variables and procedures once and then reuse them whenever needed. For example, if you want to add a spelling checker to an application you could define all the variables and support functions to provide spell-checking functionality. If you create your spelling checker as a class, you can then reuse it in other applications by adding a reference to the compiled assembly. Better yet, you may be able to save yourself some work by using a spelling checker class that someone else has already developed.

The .NET Framework provides many examples of components that are available for use. The following example uses the TimeZone class in the System namespace. TimeZone provides members that allow you to retrieve information about the time zone of the current computer system.

Public Sub examineTimeZone() Dim tz As System.TimeZone = System.TimeZone.CurrentTimeZone Dim s As String = "Current time zone is " s &= CStr(tz.GetUtcOffset(Now).Hours) & " hours and " s &= CStr(tz.GetUtcOffset(Now).Minutes) & " minutes " s &= "different from UTC (coordinated universal time)" s &= vbCrLf & "and is currently " If tz.IsDaylightSavingTime(Now) = False Then s &= "not " s &= "on ""summer time""." MsgBox(s)End Sub

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 19: Classes and Objects in VB2010

In the preceding example, the first Dim Statement (Visual Basic) declares an object variable of type TimeZone and assigns to it a TimeZone object returned by the CurrentTimeZone property.

Relationships Among Objects

Objects can be related to each other in several ways. The principal kinds of relationship are hierarchical and containment.

Hierarchical Relationship

When classes are derived from more fundamental classes, they are said to have a hierarchical relationship. Class hierarchies are useful when describing items that are a subtype of a more general class.

In the following example, suppose you want to define a special kind of Button that acts like a normal Button but also exposes a method that reverses the foreground and background colors.

To define a class is derived from an already existing class

1. Use a Class Statement (Visual Basic) to define a class from which to create the object you need.

Public Class reversibleButton

Be sure an End Class statement follows the last line of code in your class. By default, the integrated development environment (IDE) automatically generates an End Class when you enter a Class statement.

2. Follow the Class statement immediately with an Inherits Statement. Specify the class from which your new class derives.

Inherits System.Windows.Forms.Button

Your new class inherits all the members defined by the base class.

3. Add the code for the additional members your derived class exposes. For example, you might add a reverseColors method, and your derived class might look as follows:

4. Public Class reversibleButton5. Inherits System.Windows.Forms.Button6. Public Sub reverseColors() 7. Dim saveColor As System.Drawing.Color = Me.BackColor8. Me.BackColor = Me.ForeColor9. Me.ForeColor = saveColor10. End Sub

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 20: Classes and Objects in VB2010

11. End Class

If you create an object from the reversibleButton class, it can access all the members of the Button class, as well as the reverseColors method and any other new members you define on reversibleButton.

Derived classes inherit members from the class they are based on, allowing you to add complexity as you progress in a class hierarchy. For more information, see Inheritance Basics (Visual Basic).

Compiling the Code

Be sure the compiler can access the class from which you intend to derive your new class. This might mean fully qualifying its name, as in the preceding example, or identifying its namespace in an Imports Statement (.NET Namespace and Type). If the class is in a different project, you might need to add a reference to that project. For more information, see Referencing Namespaces and Components.

Containment Relationship

Another way that objects can be related is a containment relationship. Container objects logically encapsulate other objects. For example, the OperatingSystem object logically contains a Version object, which it returns through its Version property. Note that the container object does not physically contain any other object.

Collections

One particular type of object containment is represented by collections. Collections are groups of similar objects that can be enumerated. Visual Basic supports a specific syntax in the For Each...Next Statement (Visual Basic) that allows you to iterate through the items of a collection. Additionally, collections often allow you to use an Item to retrieve elements by their index or by associating them with a unique string. Collections can be easier to use than arrays because they allow you to add or remove items without using indexes. Because of their ease of use, collections are often used to store forms and controls.

Overloaded Properties and Methods

Overloading is the creation of more than one procedure, instance constructor, or property in a class with the same name but different argument types.

Overloading Usage

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 21: Classes and Objects in VB2010

Overloading is especially useful when your object model dictates that you employ identical names for procedures that operate on different data types. For example, a class that can display several different data types could have Display procedures that look like this:

Overloads Sub Display(ByVal theChar As Char) ' Add code that displays Char data.End SubOverloads Sub Display(ByVal theInteger As Integer) ' Add code that displays Integer data.End SubOverloads Sub Display(ByVal theDouble As Double) ' Add code that displays Double data.End Sub

Without overloading, you would need to create distinct names for each procedure, even though they do the same thing, as shown next:

Sub DisplayChar(ByVal theChar As Char) ' Add code that displays Char data.End SubSub DisplayInt(ByVal theInteger As Integer) ' Add code that displays Integer data.End SubSub DisplayDouble(ByVal theDouble As Double) ' Add code that displays Double data.End Sub

Overloading makes it easier to use properties or methods because it provides a choice of data types that can be used. For example, the overloaded Display method discussed previously can be called with any of the following lines of code:

' Call Display with a literal of type Char.Display("9"c)' Call Display with a literal of type Integer.Display(9)' Call Display with a literal of type Double.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 22: Classes and Objects in VB2010

Display(9.9R)

At run time, Visual Basic calls the correct procedure based on the data types of the parameters you specify.

Overloading Rules

You create an overloaded member for a class by adding two or more properties or methods with the same name. Except for overloaded derived members, each overloaded member must have different parameter lists, and the following items cannot be used as a differentiating feature when overloading a property or procedure:

Modifiers, such as ByVal or ByRef, that apply to a member, or parameters of the member.

Names of parameters Return types of procedures

The Overloads keyword is optional when overloading, but if any overloaded member uses the Overloads keyword, then all other overloaded members with the same name must also specify this keyword.

Derived classes can overload inherited members with members that have identical parameters and parameter types, a process known as shadowing by name and signature. If the Overloads keyword is used when shadowing by name and signature, the derived class's implementation of the member will be used instead of the implementation in the base class, and all other overloads for that member will be available to instances of the derived class.

If the Overloads keyword is omitted when overloading an inherited member with a member that has identical parameters and parameter types, then the overloading is called shadowing by name. Shadowing by name replaces the inherited implementation of a member, and it makes all other overloads unavailable to instances of the derived class and its decedents.

The Overloads and Shadows modifiers cannot both be used with the same property or method.

Example

The following example creates overloaded methods that accept either a String or Decimal representation of a dollar amount and return a string containing the sales tax.

To use this example to create an overloaded method

1. Open a new project and add a class named TaxClass.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 23: Classes and Objects in VB2010

2. Add the following code to the TaxClass class.

Public Class TaxClass Overloads Function TaxAmount(ByVal decPrice As Decimal, ByVal TaxRate As Single) As String TaxAmount = "Price is a Decimal. Tax is $" & (CStr(decPrice * TaxRate)) End Function

Overloads Function TaxAmount(ByVal strPrice As String, ByVal TaxRate As Single) As String TaxAmount = "Price is a String. Tax is $" & CStr((CDec(strPrice) * TaxRate)) End FunctionEnd Class

3. Add the following procedure to your form.

Sub ShowTax() ' 8% tax rate. Const TaxRate As Single = 0.08 ' $64.00 Purchase as a String. Dim strPrice As String = "64.00" ' $64.00 Purchase as a Decimal. Dim decPrice As Decimal = 64 Dim aclass As New TaxClass 'Call the same method with two different kinds of data. MsgBox(aclass.TaxAmount(strPrice, TaxRate)) MsgBox(aclass.TaxAmount(decPrice, TaxRate))End Sub

4. Add a button to your form and call the ShowTax procedure from the Button1_Click event of the button.

5. Run the project and click the button on the form to test the overloaded ShowTax procedure.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 24: Classes and Objects in VB2010

At run time, the compiler chooses the appropriate overloaded function that matches the parameters being used. When you click the button, the overloaded method is called first with a Price parameter that is a string and the message, "Price is a String. Tax is $5.12" is displayed. TaxAmount is called with a Decimal value the second time and the message, "Price is a Decimal. Tax is $5.12" is displayed.

Inheritance Basics (Visual Basic)

Visual Studio 2010 Other Versions

4 out of 4 rated this helpful - Rate this topic

The Inherits statement is used to declare a new class, called a derived class, based on an existing class, known as a base class. Derived classes inherit, and can extend, the properties, methods, events, fields, and constants defined in the base class. The following section describes some of the rules for inheritance, and the modifiers you can use to change the way classes inherit or are inherited:

By default, all classes are inheritable unless marked with the NotInheritable keyword. Classes can inherit from other classes in your project or from classes in other assemblies that your project references.

Unlike languages that allow multiple inheritance, Visual Basic allows only single inheritance in classes; that is, derived classes can have only one base class. Although multiple inheritance is not allowed in classes, classes can implement multiple interfaces, which can effectively accomplish the same ends.

To prevent exposing restricted items in a base class, the access type of a derived class must be equal to or more restrictive than its base class. For example, a Public class cannot inherit a Friend or a Private class, and a Friend class cannot inherit a Private class.

Inheritance Modifiers

Visual Basic introduces the following class-level statements and modifiers to support inheritance:

Inherits statement — Specifies the base class. NotInheritable modifier — Prevents programmers from using the class as a base class. MustInherit modifier — Specifies that the class is intended for use as a base class only.

Instances of MustInherit classes cannot be created directly; they can only be created as base class instances of a derived class. (Other programming languages, such as C++ and C#, use the term abstract class to describe such a class.)

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 25: Classes and Objects in VB2010

Overriding Properties and Methods in Derived Classes

By default, a derived class inherits properties and methods from its base class. If an inherited property or method has to behave differently in the derived class it can be overridden. That is, you can define a new implementation of the method in the derived class. The following modifiers are used to control how properties and methods are overridden:

Overridable — Allows a property or method in a class to be overridden in a derived class.

Overrides — Overrides an Overridable property or method defined in the base class. NotOverridable — Prevents a property or method from being overridden in an inheriting

class. By default, Public methods are NotOverridable. MustOverride — Requires that a derived class override the property or method. When

the MustOverride keyword is used, the method definition consists of just the Sub, Function, or Property statement. No other statements are allowed, and specifically there is no End Sub or End Function statement. MustOverride methods must be declared in MustInherit classes.

Suppose you want to define classes to handle payroll. You could define a generic Payroll class that contains a RunPayroll method that calculates payroll for a typical week. You could then use Payroll as a base class for a more specialized BonusPayroll class, which could be used when distributing employee bonuses.

The BonusPayroll class can inherit, and override, the PayEmployee method defined in the base Payroll class.

The following example defines a base class, Payroll, and a derived class, BonusPayroll, which overrides an inherited method, PayEmployee. A procedure, RunPayroll, creates and then passes a Payroll object and a BonusPayroll object to a function, Pay, that executes the PayEmployee method of both objects.

Const BonusRate As Decimal = 1.45DConst PayRate As Decimal = 14.75D

Class Payroll Overridable Function PayEmployee( ByVal HoursWorked As Decimal, ByVal PayRate As Decimal) As Decimal

PayEmployee = HoursWorked * PayRate End FunctionEnd Class

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 26: Classes and Objects in VB2010

Class BonusPayroll Inherits Payroll Overrides Function PayEmployee( ByVal HoursWorked As Decimal, ByVal PayRate As Decimal) As Decimal

' The following code calls the original method in the base ' class, and then modifies the returned value. PayEmployee = MyBase.PayEmployee(HoursWorked, PayRate) * BonusRate End FunctionEnd Class

Sub RunPayroll() Dim PayrollItem As Payroll = New Payroll Dim BonusPayrollItem As New BonusPayroll Dim HoursWorked As Decimal = 40

MsgBox("Normal pay is: " & PayrollItem.PayEmployee(HoursWorked, PayRate)) MsgBox("Pay with bonus is: " & BonusPayrollItem.PayEmployee(HoursWorked, PayRate))End Sub

The MyBase Keyword

The MyBase keyword behaves like an object variable that refers to the base class of the current instance of a class. MyBase is frequently used to access base class members that are overridden or shadowed in a derived class. In particular, MyBase.New is used to explicitly call a base class constructor from a derived class constructor.

For example, suppose you are designing a derived class that overrides a method inherited from the base class. The overridden method can call the method in the base class and modify the return value as shown in the following code fragment:

Class DerivedClass Inherits BaseClass Public Overrides Function CalculateShipping( ByVal Dist As Double, ByVal Rate As Double) As Double

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 27: Classes and Objects in VB2010

' Call the method in the base class and modify the return value. Return MyBase.CalculateShipping(Dist, Rate) * 2 End FunctionEnd Class

The following list describes restrictions on using MyBase:

MyBase refers to the immediate base class and its inherited members. It cannot be used to access Private members in the class.

MyBase is a keyword, not a real object. MyBase cannot be assigned to a variable, passed to procedures, or used in an Is comparison.

The method that MyBase qualifies does not have to be defined in the immediate base class; it may instead be defined in an indirectly inherited base class. In order for a reference qualified by MyBase to compile correctly, some base class must contain a method matching the name and types of parameters that appear in the call.

You cannot use MyBase to call MustOverride base class methods. MyBase cannot be used to qualify itself. Therefore, the following code is not valid:

MyBase.MyBase.BtnOK_Click()

MyBase cannot be used in modules. MyBase cannot be used to access base class members that are marked as Friend if the

base class is in a different assembly.

For more information and another example, see How to: Access a Variable Hidden by a Derived Class (Visual Basic).

The MyClass Keyword

The MyClass keyword behaves like an object variable that refers to the current instance of a class as originally implemented. MyClass resembles Me, but every method and property call on MyClass is treated as if the method or property were NotOverridable (Visual Basic). Therefore, the method or property is not affected by overriding in a derived class.

MyClass is a keyword, not a real object. MyClass cannot be assigned to a variable, passed to procedures, or used in an Is comparison.

MyClass refers to the containing class and its inherited members. MyClass can be used as a qualifier for Shared members. MyClass cannot be used inside a Shared method, but can be used inside an instance

method to access a shared member of a class. MyClass cannot be used in standard modules.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 28: Classes and Objects in VB2010

MyClass can be used to qualify a method that is defined in a base class and that has no implementation of the method provided in that class. Such a reference has the same meaning as MyBase.Method.

The following example compares Me and MyClass.

Class baseClass Public Overridable Sub testMethod() MsgBox("Base class string") End Sub Public Sub useMe() ' The following call uses the calling class's method, even if ' that method is an override. Me.testMethod() End Sub Public Sub useMyClass() ' The following call uses this instance's method and not any ' override. MyClass.testMethod() End SubEnd ClassClass derivedClass : Inherits baseClass Public Overrides Sub testMethod() MsgBox("Derived class string") End SubEnd ClassClass testClasses Sub startHere() Dim testObj As derivedClass = New derivedClass() ' The following call displays "Derived class string". testObj.useMe() ' The following call displays "Base class string". testObj.useMyClass() End SubEnd Class

Even though derivedClass overrides testMethod, the MyClass keyword in useMyClass nullifies the effects of overriding, and the compiler resolves the call to the base class version of testMethod.

Me, My, MyBase, and MyClass in Visual Basic

Visual Studio 2010 Other Versions

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 29: Classes and Objects in VB2010

1 out of 3 rated this helpful - Rate this topic

Me, My, MyBase, and MyClass in Visual Basic have similar names, but different purposes. This topic describes each of these entities in order to distinguish them.

Me

The Me keyword provides a way to refer to the specific instance of a class or structure in which the code is currently executing. Me behaves like either an object variable or a structure variable referring to the current instance. Using Me is particularly useful for passing information about the currently executing instance of a class or structure to a procedure in another class, structure, or module.

For example, suppose you have the following procedure in a module.

Sub ChangeFormColor(FormName As Form) Randomize() FormName.BackColor = Color.FromArgb(Rnd() * 256, Rnd() * 256, Rnd() * 256)End Sub

You can call this procedure and pass the current instance of the Form class as an argument by using the following statement.

ChangeFormColor(Me)My

The My feature provides easy and intuitive access to a number of .NET Framework classes, enabling the Visual Basic user to interact with the computer, application, settings, resources, and so on.

MyBase

The MyBase keyword behaves like an object variable referring to the base class of the current instance of a class. MyBase is commonly used to access base class members that are overridden or shadowed in a derived class. MyBase.New is used to explicitly call a base class constructor from a derived class constructor.

MyClass

The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented. MyClass is similar to Me, but all method calls on it are treated as if the method were NotOverridable.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 30: Classes and Objects in VB2010

How to: Create an Array of Objects (Visual Basic)

Every object is a reference type. You declare and use an array of a reference type just as you would declare and use an array of any data type. The elements of an object type array can be retrieved by their index and can be manipulated as any object of the given type would be.

Arrays also have built-in functionality for searching and sorting that can be accessed through the array variable. For more information on these methods, see Array.

To create an array of objects

1. Declare the array as shown in the following example. Because arrays are zero-based, they contain one element more than the upper bound you declare.

2. Dim x(10) As widget3. ' x now contains 11 elements of type widget, x(0) through x(10).4. Create each element of the array, or assign to each element a reference to an already

existing object. The following example demonstrates this.5. ' Create each element of an array by using a loop.6. For q As Integer = 0 To 107. x(q) = New widget()8. Next q9. ' Assign a reference to an existing object to two array elements.10. Dim specialWidget As New widget()11. x(0) = specialWidget12. x(1) = specialWidget

Note that you can assign references to the same object to different elements of the array.

How to use Microsoft Visual Basic .NET to connect to a Microsoft Access database and to retrieve data

Article ID: 821765 - View products that this article applies to.Expand all | Collapse all

On This Page

SUMMARY

This step-by-step article describes how to use Microsoft ADO.NET to open a Microsoft Access database by using the OLE DB data provider. You use the OleDbDataAdapter class to obtain rows from the Access database and to insert the rows into a DataSet object. This article describes how to add rows, how to delete rows, and how to update rows in the Access database by using DataSet and OleDbDataAdapter.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 31: Classes and Objects in VB2010

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:

Microsoft .NET Framework Microsoft Visual Basic .NET Microsoft Access

This article assumes that you are familiar with the following topics:

Visual Basic .NET ADO.NET Access

Create a Microsoft Access database

To create a database in Access and then create a table in the database, follow these steps:

1. Start Access.2. On the File menu, click New.3. Click Blank database on the task pane.4. In the File name box, type testdb, and then click Create.5. Right-click Create table in Design view, and then click Open.6. In the Field Name text box, type SName. 7. In the Data Type list, click Text.8. In the Field Name text box, type SNo. 9. In the Data Type list, click Number.10. Right-click SNo, and then click Primary Key.11. On the File menu, click Save As. 12. In the Save As dialog box, type Student in the text box and then click OK. Close

the design view.13. Right-click the Student table, and then click Open.14. Type ABC in the SName column.15. Type 101 in the SNo column.16. Type XYZ in the SName column.17. Type 102 in the SNo column.18. Type several more records in the Student table, and then close the Student:Table

window.19. Close the testdb database.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 32: Classes and Objects in VB2010

Create a connection to the Access database by using Visual Basic .NET

The following step-by-step example describes how to create a connection to the Access database by using the Microsoft Visual Studio .NET Server Explorer. The following example also describes how to use the OleDbDataAdapter class to retrieve data from the database and to insert data into a DataSet object. This example also describes how to create new rows, how to add these rows to the table, how to modify the data in the rows, and how to remove rows from the table in the Access database.

Create a Windows application in Visual Basic .NET

1. Start Microsoft Visual Studio .NET.2. On the File menu, point to New, and then click Project.3. Under Project Types, click Visual Basic Projects. 4. Under Templates, click Windows Application, and then click OK.

By default, Form1 is created.

Open a connection to the Access database

1. On the View menu, click Server Explorer.2. In Server Explorer, right-click Data Connections, and then click Add Connection.3. In the Data Link Properties dialog box, click the Provider tab. 4. In the OLE DB Provider(s) list, click Microsoft Jet 4.0 OLE DB Provider, and then

click Next.5. Click the Connection tab, and then click the ellipses button (...). 6. Locate the Access database testdb.mdb file that you created by following the

corresponding path on your computer. 7. Select the testdb.mdb file, and then click Open.8. In the Data Link Properties dialog box, click OK.

Retrieve data from the Access database by using the OleDbDataAdapter class

1. On the toolbox, click the Data tab.2. Drag an OleDbDataAdapter control to Form1.3. In the Data Adapter Configuration Wizard, click Next three times.4. In the Generate the SQL statements panel, type the following Microsoft SQL

Server statement, and then click Next:

Select * from Student

5. In the View Wizard Results panel, click Finish.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 33: Classes and Objects in VB2010

Note In the Do you want to include the password in the connection string? dialog box, click Don't include password.

6. Right-click OleDbDataAdapter1, and then click Generate Dataset. 7. In the Generate Dataset dialog box, click OK.8. Add the following code to the Form1_Load event handler:9. 'Fill retrieves rows from the data source by using the SELECT statement

OleDbDataAdapter1.Fill(DataSet11)

Display records that are retrieved from the Access database

1. Add a DataGrid control to Form1.

By default, DataGrid1 is created.2. Right-click DataGrid1, and then click Properties.3. In the Properties dialog box, set the DataSource property to DataSet11 and set

the DataMember property to Student.

Add a row to a table in the Access database

1. Add a Button control to Form1.2. Right-click Button1, and then click Properties.3. In the Properties dialog box, set the Text property to Add.4. Add the following code to the Button1_Click event handler:5. Dim i, sno As Integer6. Dim sname As String7. Dim rw As DataRow8. 'Add a new row to the Student table.9. rw = DataSet11.Tables(0).NewRow10. sno = InputBox("Enter the Roll no of the Student:")11. sname = InputBox("Enter the Name of the Student:")12. rw.Item("SNo") = sno13. rw.Item("SName") = sname14. Try15. DataSet11.Tables(0).Rows.Add(rw)16. 'Update the Student table in the testdb database.17. i = OleDbDataAdapter1.Update(DataSet11)18. Catch ex As Exception19. MessageBox.Show(ex.Message)20. End Try21. 'Displays number of rows updated.

MessageBox.Show("no of rows updated=" & i)

Update the rows of a table in the Access database

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 34: Classes and Objects in VB2010

1. Add a Button control to Form1.

By default, Button2 is created.2. Right-click Button2, and then click Properties.3. In the Properties dialog box, set the Text property to Update.4. Add the following code to the Button2_Click event handler:5. Dim i, rwno As Integer6. Dim colname As String7. Dim value As Object8. colname = InputBox("Enter the name of the Column to be updated")9. rwno = InputBox("Enter the Row Number to be updated: Row No starts from 0")10. value = InputBox("Enter the value to be entered into the Student table")11. Try12. 'Update the column in the Student table.13. DataSet11.Tables(0).Rows(rwno).Item(colname) = value14. 'Update the Student table in the testdb database.15. i = OleDbDataAdapter1.Update(DataSet11)16. Catch ex As Exception17. MessageBox.Show(ex.Message)18. End Try19. 'Displays number of rows updated.20. MessageBox.Show("no of rows updated=" & i)

Delete rows from a table in the Access database

1. Add a Button control to Form1.

By default, Button3 is created.2. Right-click Button3, and then click Properties.3. In the Properties dialog box, set the Text property to Delete.4. Add the following code to the Button3_Click event handler:5. Dim i As Integer6. Dim rno As Integer7. rno = InputBox("Enter the Row no to be deleted: Row no starts from 0")8. Try9. 'Delete a row from the Student table.10. DataSet11.Tables(0).Rows(rno).Delete()11. 'Update the Student table in the testdb database.12. i = OleDbDataAdapter1.Update(DataSet11)13. Catch ex As Exception14. MsgBox(ex.Message)15. End Try16. 'Displays number of rows updated.

MessageBox.Show("no of rows updated=" & i)

Sources: http://msdn.microsoft.com/en-us/library/vstudio/

Page 35: Classes and Objects in VB2010

Verify that it works

1. On the Build menu, click Build Solution.2. On the Debug menu, click Start.3. Click Add, and then type the data in the input box to add a row to the Student

table.

Note: You receive an error if you click Cancel in the input boxes.4. Click Update, and then type the data in the input boxes to update a column in the

Student table.5. Click Delete, and then type the data in the corresponding input boxes to delete a

row from the Student table.

Sources: http://msdn.microsoft.com/en-us/library/vstudio/