Visual Basic.NET Language Enhancements: Polymorphism

Category:
C#, VB.NET, ASP.NET
Type:
Snippets
Difficulty:
Beginning

Author: Intelligent Solutions Inc.

Version Compatibility: Visual Basic.NET

More information:
This is Part 2 of 5 mini-articles that were originally published in the FreeVBCode.com newsletter about language enhancements in Visual Basic.NET

Instructions: Copy the declarations and code below and paste directly into your VB project.

Polymorphism

This is part 2 in a series on new language features in Visual Basic.NET. In Part 1, inheritance was covered. To briefly review, inheritance allows you to re-use code from a parent (or base) class in a child class. This article presented an example of a child class, clsMyValidate, that inherited all the functionality from a parent class, clsValidate.

Polymorphism is related to inheritance. The term refers to the ability of functions in child classes with the same name as those in parent classes to behave differently in the child.

For instance, in the example discussed in Part 1, the parent class had a number of functions which the child class wanted to use as coded, but it also included some custom, business related validation functions of its own. Thus, the child class included the following statement in its declarations section:

Inherits clsValidate

Now, lets say that the child class wants to use all of the functions in clsValidate as written, except it needs to modify one. For the purposes of illustration, lets say the parent class has a function called IsAlphaNumeric, which returns true if a string contains only alphabetical or numeric characters. The child class likes this OK, but also wants to return true if the string contains numeric qualifiers such as $, %, or a decimal point. The child class can override the parent class in this manner:

'In Declarations

Inherits clsValidate

Function IsAlphaNumeric (Input as String)
Overrides Function IsAlphaNumeric
'appropriate code
End Function

This is polymorphism: The function in the child class will, under certain circumstances, behave differently than the same function in the parent class.

The advantages of this technique are numerous. For instance, the child class can still take advantage of all the other functions in the parent class without having to be written from the ground up. In addition, other classes that are conceptually similar to the parent class can override functions in the parent class as needed. Finally, say there are a 100 applications which are clients of clsMyValidate (the child). If the business rule changes as described above, the class developer can use polymorphism, instead of destroying up the whole inheritance structure. And the clients can continue to call IsAlphaNumeric as usual, with no changes in their code.

The rest of the series:

Part I, Inheritance
Part III, Overloading
Part IV, Constructors
Part V, Free Threading