.net.devcity.weekly ---
If you are unable to see the message, visit http://www.devcity.net/newsletter/archive/devcity/devcity20040905.htm

Advertisement

AdvertisementAdvertisement

The newsletter is compiled by DevCity.NET NewsMasters Ged Mead and Mike McIntyre

I've spent last four weeks traveling. First week in Paris was just amazing - I love this city! I'm in the Ukraine now and returning back to Seattle next week.

While traveling I was thinking that it would be great to go to all the countries and cities of vbCity members, but obviously I'm not going to have enough time nor money to make this possible. So I have a bit unusual request. I ask you all to help me with a worthy substitute - POSTCARDS

I would absolutely love to get a postcard (real postcards, cardboard ones) from every city that has a vbCity member. Or a photo of the city, or a photo of you in the city. Go crazy. Something that I can pin on a wall in my home office and stare at.

Send your postcards to:

vbCity.com
4957 Lakemont Blvd SE C4 #331
Bellevue, WA 98006
USA

Thanks everyone!
Serge Baranovsky, the (g)host of vbCity.com

Advertisement

Table Of Content:

Advertisement

by Mike McIntyre

This five part article discusses the use of the methods and constants of the Microsoft.VisualBasic run-time assembly (VisualBasic) in terms of purpose, performance, and coding standards.

This article compares VisualBasic methods to their .NET Framework Class Library (FCL) equivalents so a programmer can learn to make choices based on purpose, performance, and coding standards. Where a VisualBasic method or constant has a FCL equivalent, a Visual Basic programmer has a choice; use the VisualBasic method or constant - or use a FCL equivalent.

Testing Process

Each VisualBasic method and its FCL equivalent were implemented in a Windows Forms performance testing application. Sample code for testing the methods came from the Visual Studio Help topics which cover the VisualBasic methods.

FCL equivalents were found in or built from the FCL. Each VisualBasic method's implementation was examined with a decompiler 'as is' in the VisualBasic DLL and again after it was compiled into the Windows Application. The decompilations were used to find a FCL equivalent method or, if not found, to build a FCL equivalent from FCL classes.

Warning: Performance results vary depending on how a method is used in code. If you encounter a performance bottleneck you may need to 1) refactor your code or, 2) switch from a VisualBasic method to a FCL method or vice versa.

Err and IsError Functions

Purpose: Err contains information about run-time errors. IsError returns a Boolean value indicating whether an expression is an exception type.

Recommendation: Use these functions for legacy code only. For new code use the FCL Exception classes and Try..Catch..Finally exception blocks. Exceptions and exception handling are used to handle errors in .NET. Learn more here.

IsArray Function

Purpose: IsArray returns True if the variable points to an array; otherwise, it returns False.

Recommendation: Unless disallowed by coding standards use IsArray. IsArray is typically much faster than using FCL equivalents.

IsDate Function

Purpose: Returns a Boolean value indicating whether an expression can be converted to a date.

Recommendation: Unless disallowed by coding standards use IsDate. IsDate is typically much faster than using FCL equivalents. The IsDate implementation is solid:

  1. Receives an object argument.
  2. Verifies object is not Nothing.
  3. Verifies object is convertible.
  4. Verifies object can be converted to a date type.

IsDBNull Function

Purpose: Returns a Boolean value indicating whether an expression evaluates to the System.DBNull class.

Recommendation: Unless disallowed by coding standards use IsDBNull. IsDBNull is typically much faster than using FCL equivalents.

IsNothing Function

Purpose: Returns a Boolean value indicating whether an expression has no object assigned to it.

Recommendation: Unless disallowed by coding standards use IsNothing or its FCL equivalent, performance and implementation are equal.

IsNumeric Function

Purpose: Returns a Boolean value indicating whether an expression can be evaluated as a number.

Recommendation: Unless disallowed by coding standards use IsNumeric. IsNumeric is typically much faster than using FCL equivalents. The IsNumeric implementation is solid:

  1. Receives an object argument.
  2. Verifies object is not Nothing.
  3. Verifies object is convertible to number type.
  4. OR - verifies object can be parsed to a number type.

Learn more about the members of the VisualBasic assembly here.

by George Poth

You will see the Property Pages for your project. In the left pane, select General from the Common Properties folder. There is a combo box with the name Output type. Open it and select the output type you want.

If you are using the Standard Edition, then you will only have the choice between Windows Application and Console Application, poor boy. I do not know if this changes if you install other templates, neither do I know whether it is different in the 2003 Standard Edition. I do know that it is also quite simple to change.

Open the folder that contains your project. If XP is your operating system, you need to look for the file with the description Visual Basic .NET Project. On other operating systems, you might have to look for the .vbproj extension

Open the folder that contains your project. If XP is your operating system, you need to look for the file with the description Visual Basic .NET Project. On other operating systems, you might have to look for the .vbproj extension.

Right click this file and open it with Notepad. Change the lines that read OutputType = "WinExe" to OutputType = "Library" and StartupObject = "YourApplicationName.YourFormName" to StartupObject = "". Save the changes and close this file. When you get back to the IDE, you will see a message giving you the choice to reload or to ignore the changes. Click to reload and then build the project. Now you have a dll in your bin folder.

Things are very easy, though a pain in the whatsit if you are using SharpDevelop. All projects build as Exe (Console Application) by default. The developers certainly come from a C/C++ background - it is a C developer's mania, the console application. I do not know why they love consoles so much, but they really do. Anyway, select Project Options from the Project menu. Open the Configuration folder and select Output. Select your project type from the corresponding combo box and build your project.

As you can see, changing the output type of your application is very easy. If you have invested quite some cash, then it will be as simple as clicking; if not, you have to do some extra work. Who cares? Important is that you know how to do it.

Why would someone want to turn an application into a library? Imagine you have developed something that you would like to add to all your programs. This could be an "About" form for instance. As a patient programmer, you can develop a generic "About" form that gets all the necessary information from the application to which you have added it. There is no need to make any changes. You should make a .dll with such a classical candidate because you can reference to it in your application and use it as you would use any other form - or almost so.

Making such a generic "About" form is impossible! Actually, it is not quite that difficult. You have probably observed that I have started an article series for beginning programmers, and such an "About" form, although to some extent simplified, will be part of it. The bad news is that until we get there, it will take some time. Then again, you are a patient programmer, right?

Diary of a .NET Newbie: Default's The Fault

by Ged Mead

I was trying to help someone out the other day. What he was asking for didn't seem to be too difficult and although it was something I hadn't tackled before, I was confident that I could find an answer fairly quickly.

He had a Treeview with one root node and six child nodes. What he wanted to do was to have the third child node automatically selected when the form loaded. So the Treeview's display would look something like:

+City
     Rome
     Paris
     Delhi
     Berlin
     London
     Washington

And "Delhi" would be selected and highlighted.

Now, I'm betting here that I'm not the only one who has sometimes found nested nodes in Treeviews can be tricky little critters. However, I know that the Node Collection concept is really very logical and it's usually just a matter of taking it one step at a time. In my case, a very slow, tentative step, checking for pitfalls with my toecap as I shuffle along. But if you think of each individual node as being a completely separate entity (and not as a Treeview element) then the idea becomes much easier to handle.

Thinking that it was going to be easy to make this default selection, I came up with this:

Dim CityNode As TreeNode = TreeView1.Nodes.Item(3)
TreeView1.SelectedNode = CityNode

However, as anyone with experience of Treeviews will already know, the only reward I got for that was an "Argument Out of Range Exception" message:

      Specified argument was out of the range of valid values.

The reason is this. As far as the Treeview is concerned, there is no

TreeView1.Nodes.Item(3)

It only has one first level node (the one named "City"), so the only index it would accept would be 0.

TreeView1.Nodes.Item(0)

However, that would only select the "City" first level node, which obviously is not what we wanted.
Bottom line: You can't access those Sub Nodes with code like that.

So, a quick adjustment was needed to make the code go one level deeper and enumerate through those six capital cities until it reached the third one. At that point it would select and highlight that node, the one with the text value of "Delhi".

This code should do the trick, I thought:

'  Instantiate a TreeNode variable for the Root Node (City)
Dim CityNode As TreeNode = TreeView1.Nodes.Item(0)

' Instantiate a second variable to be used to enumerate
' through all the child nodes of the root node
Dim node As TreeNode

' Enumerate through all the child nodes of "City"
For Each node In CityNode.Nodes
    ' When you find the third one, select it.
    If node.Index = 2 Then TreeView1.SelectedNode = node
Next

But, strangely, that didn't seem to be working properly either. OK, I was no longer getting an error message, but I wasn't getting the planned result either. The third child item "Delhi" wasn't being highlighted.

Was it in fact being selected, I wondered?

A quick and dirty test using a messagebox showed that the correct node ("Delhi") was indeed being selected:

Dim CityNode As TreeNode = TreeView1.Nodes.Item(0)
Dim node As TreeNode
For Each node In CityNode.Nodes
    If node.Index = 2 Then TreeView1.SelectedNode = node
Next
MessageBox.Show(TreeView1.SelectedNode.Text)

But why didn't it appear to be so to the user?

The answer - as usual - was fairly simple and is another little Gotcha lurking out there to trip up the unwary .NET Newbie. The Treeview control has a Boolean property named "HideSelection". Obviously, that is exactly what it does do if it is set to True; it hides the fact that a node has been selected (i.e. it selects it, but doesn't highlight it on the screen).

And the Default setting of this property is......
Ah, I see you're way ahead of me as usual ....
Yep! The default setting is: True.

So, changing the HideSelection property to False at design time was all that was needed to get everything back on course and the question answered.

It does help to remind us, though, that you still have to be on your guard for little trip-ups like these, even when the original question seems so very easy. As with many things in VB.Net, things are not always as straightforward as they seem. You think you have all the information you need, but then discover that there is one vital piece missing at the very end, if you see what I

- Junior (Ged Mead aka XTab, xtab@vbcity.com)

.NET Newbies: Select Case tricks...

by Dries Neyrinck

1. Replace those large "If Then ElseIf End If" blocks!

Suppose you have three radiobuttons on your form. As a user you have to select one to continue the program. If we want to check which radiobutton was selected we would end up writing a big unwieldy If...Then...Else equation like this:

If Me.RadioButton1.Checked Then
    MessageBox.Show("You selected radiobutton 1")
ElseIf Me.RadioButton2.Checked Then
    MessageBox.Show("You selected radiobutton 2")
ElseIf Me.RadioButton3.Checked Then
    MessageBox.Show("You selected radiobutton 3")
Else
    MessageBox.Show("You didn't select an option!!")
End If

While this works perfectly there's a more elegant and easy solution available!

Select Case True

    Case Me.RadioButton1.Checked
        MessageBox.Show("You selected radiobutton 1")
    Case Me.RadioButton2.Checked
        MessageBox.Show("You selected radiobutton 2")
    Case Me.RadioButton3.Checked
        MessageBox.Show("You selected radiobutton 3")
    Case Else
        MessageBox.Show("You didn't select an option!!")

End Select

OK, this is a little funny to read perhaps, but once you look again into the statement is makes perfect sense.

What does the official MSDN documentation say?

Executes one of several groups of statements, depending on the value of an expression.

Select [ Case ] testexpression
   [ Case expressionlist
      [ statements ] ]
   [ Case Else
      [ elsestatements ] ]
End Select

Parts

testexpression - Required. Expression. Must evaluate to one of the elementary data types (Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, Short, Single, and String).

expressionlist - Required in a Case statement. List of expression clauses representing match values for testexpression. Multiple expression clauses are separated by commas. Each clause can take one of the following forms:

  • expression1 To expression2
  • [ Is ] comparisonoperator expression
  • expression

statements - Optional. One or more statements following Case that are executed if testexpression matches any clause in expressionlist.

elsestatements - Optional. One or more statements following Case Else that are executed if testexpression does not match any clause in the expressionlist of any of the Case statements.

End Select - Terminates Select...Case block.

We use the Boolean value True as the test expression in our select case statement. This is a valid test expression, as it will always evaluate to True (or what else did you think ;-) ).

In our Case statements we show one by one the possibilities that would evaluate to True. If Radiobutton 1 is checked we will show a messagebox telling us this happy fact. Meanwhile the Select Case statement is ended in the background. The other options won't be checked further against the Test Expression since we already met the first Case statement that caused our True.

Taking this knowledge further into account, we can also evaluate against False!

Suppose you have three checkboxes on your form. All three should be checked before the user should continue. To verify this, we would write something like this:

If Not Me.CheckBox1.Checked Then
    MessageBox.Show("You didn't check checkbox 1")
ElseIf Not Me.CheckBox2.Checked Then
    MessageBox.Show("You didn't check checkbox 2")
ElseIf Not Me.CheckBox3.Checked Then
    MessageBox.Show("You didn't check checkbox 3")
Else
    MessageBox.Show("You didn't select an option!!")
End If

Once again we have a more elegant solution available with a select case statement:

Select Case False

    Case Me.CheckBox1.Checked
        MessageBox.Show("You didn't check checkbox 1")
    Case Me.CheckBox1.Checked
        MessageBox.Show("You didn't check checkbox 2")
    Case Me.CheckBox1.Checked
        MessageBox.Show("You didn't check checkbox 3")
    Case Else
        MessageBox.Show("You checked them all!!")

End Select

2. Multiple expressions or ranges in your case expressions.

Suppose you want to evaluate a number given by the user. We can do different tests here:

  • we can check if the number is equal to 1
  • we can check if the number is in a certain set of predefined numbers
  • we can check if the number is even (note the "\" operator in the code hereunder will result the integer quotient of number1 and number2, dropping the remainder)
  • we can check if the number fits in a range

This results in following code:

Select Case Int32.Parse(Me.TextBox1.Text)
    Case 1
        MessageBox.Show("1!")
    Case 2, 7, 11, 13, 17, 19
        MessageBox.Show("Prime under 20!")
    Case 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
        MessageBox.Show("Prime over 20!")
    Case (Int32.Parse(Me.TextBox1.Text) \ 2) * 2
        MessageBox.Show("Even number!")
    Case 24 To 28
        MessageBox.Show("Between 24 and 28")
    Case Else
        MessageBox.Show("Just another number!")
End Select

Do the test and fill in following values: 1, 17, 6, 9, 25, 99. You'll get all the possible results we built into our Select case statement.

by Nino Priore, MCP

Part 3

Note: This series covers advanced topics and is not intended to be an exhaustive treatment of the subjects discussed. My intention is to provide the reader with a better understanding of the Overloads, Overrides, and Shadows keywords. Where necessary, I will refer the reader to other sources for more details. If you're a VB.Net programmer who writes software components intended for use by other programmers or applications that can be extended by other programmers, or if you use third party components or extend components written by others, you will certainly want to become more familiar with these keywords as they will allow you to leverage more of the power and flexibility built into an object oriented language like VB.NET.
This series is applicable to VB.NET programmers only. C# provides it's own flavor of support for member hiding (shadowing), virtual functions, and overloading. And since there are significant differences in the C# implementation, here we're talking only VB.NET.
Also, in these articles I use the word method to mean any procedure in VB.NET (i.e., Subs, Functions, and Property procedures).

In the last installment of this article we discussed overloading and the Overloads keyword. In this installment we discuss overriding and the Overrides keyword.

A word of warning is in order here: The topics discussed in this installment involve inheritance, virtual functions, and polymorphism. These are some of the most complex interrelated concepts you will find in an object oriented language and I reiterate that they cannot be thoroughly discussed within the confines of a short article such as this. So I will cover them only enough to explain the use of the Overrides keyword and you will want to pay attention, especially if you are new to these concepts.

Also, if you're not familiar with the concept of Inheritance, read about it here and then return to this article.

Virtual Functions

Before you can understand the use of the Overrides keyword, you have to understand the concept of Virtual Functions. The term "virtual function" is often encountered in the C++ language, not in VB.Net, but it means the same thing when discussed within the context of any object oriented language and it's implementation of inheritance. I mention it here only because it does a good job of placing a name to the concept of dynamic binding of methods in object oriented languages.

A virtual function is a method in a base class that can be redefined in a derived class. The actual binding between the call to the method and the method's implementation does not occur until run time.

It is important to understand those last two sentences, but if they are confusing to you, don't worry I'll elaborate shortly.

In VB.NET you can designate a method to be virtual by declaring it in the base class with the Overridable keyword. That keyword means that a method can be redefined (referred to as overridden in VB.Net parlance) if the designer of a derived class wishes to do so. From this point forward in this article, when I refer to a virtual function I will use the term Overridable or Overridden, so I may say "overridable property," or "overridable function," or "overridden property," etc.

In the following example we have a base class named Animal and we want to provide an Overridable property for the number of legs that the animal has. We decide that most animals will have 4 legs so we use that as the default. We also make the property read-only because we don't want to have the number of legs changed after the Animal object is instantiated. However, by making the property Overridable, we allow designers of a derived class (perhaps a Monkey class) to Override the property and specify a different number of legs.

Public Class Animal

    Protected _NumberOfLegs As Integer = 4

    Public Overridable ReadOnly Property NumberofLegs() As Integer
        Get
            Return Me._NumberOfLegs
        End Get
    End Property

End Class

The following Monkey class inherits from the Animal class and provides it's own implementation of the NumberOfLegs property. Note that in this derived class I am able to access the _NumberOfLegs variable directly in the base class and set it's value because it is a protected member; therefore, I can do that within the constructor of my derived Monkey class even though the public property is a read-only property.

Public Class Monkey : Inherits Animal

    Public Sub New()
        Me._NumberOfLegs = 2
    End Sub

    Public Overrides ReadOnly Property NumberOfLegs() As Integer
        Get
            Return Me._NumberOfLegs
        End Get
    End Property

End Class

Another way to declare an overridable method is to declare it in the base class with the MustOverride keyword, instead of the Overridable keyword. Then the method is known as a "pure virtual function" in object oriented speak, and it means the designer of a derived class must redefine the method because the base class will have only the signature of the method and no implementation details.

Also, if any method in a base class is declared with the MustOverride keyword, then the class must also be defined with the MustInherit keyword, making the class an "abstract class." An abstract class cannot be used to instantiate objects and can only be used as a base class.

This makes sense because if the base class does not define the implementation of a method, then we would not want an object of that class, since calling that method would produce no result.

In the earlier example where we used the Overridable keyword to declare the property and did not use the MustInherit keyword, it was possible to have both Animal objects and Monkey objects in our program.

Now, in this second scenario, it is not possible to have an Animal object in our program (an Animal object is an instance of the Animal class). We can have only Monkey objects because we declare the Animal class with the MustInherit keyword and provide no implementation details for the NumberOfLegs property.

Public MustInherit Class Animal

    Protected _NumberOfLegs As Integer = 4

    Public MustOverride ReadOnly Property NumberOfLegs() As Integer

End Class

Public Class Monkey : Inherits Animal

    Public Sub New()
        Me._NumberOfLegs = 2
    End Sub

    Public Overrides ReadOnly Property NumberOfLegs() As Integer
        Get
            Return Me._NumberOfLegs
        End Get
    End Property

End Class

Polymorphism

The concept of overridable methods is a powerful one and without it we could not have inheritance based polymorphism, one of the foundations of object oriented programming languages, because virtual functions (overridable methods) is the mechanism that implements polymorphic behavior in an object oriented language like VB.NET.

Polymorphism itself can be a difficult concept to understand but I'll do my best to explain it here, and later I'll show you some examples. For now, just remember that without polymorphism we could not say VB.NET is an object-oriented language.

The word "Polymorphism" literally means many forms and it's indicative of the many forms a base class can spawn in its derived classes as each derived class can extend the functionality of the base class.

Note: In this context, when we say forms we don't mean the windows that you can see on the screen when working in a visual programming environment like Visual Studio. Instead, here we are referring to the standard definition of the word as found in the dictionary: The shape and structure of something; the essence of something; a model for making a mold, etc.

The benefit of polymorphism is that at design time you do not need to know which overridable method in an inheritance chain will be called at run time. All you need to know is that if the method is called on a reference to a base class object, then the runtime can determine which method should be called based on the true type of the object assigned to the variable. This is what is meant by dynamic binding of a method and it's implementation.

That may sound confusing. I know it did when I first heard it, so let's see an example.

Here we have the same base class, but this time we have a MustOverride read-only property called RunningSpeed. This property tells us how fast a particular animal can run. Note that I declared the Animal class with the MustInherit keyword because I must to do this after I use the MustOverride keyword on any of it's methods. Also, we now have two derived classes, a Monkey class and a Dog class. You'll notice that each has a different RunningSpeed value.

Public MustInherit Class Animal

    Protected _RunningSpeed As Integer = 20

    Public MustOverride ReadOnly Property RunningSpeed() As Integer

End Class

Public Class Monkey : Inherits Animal

    Public Sub New()
        Me._RunningSpeed = 9
    End Sub

    Public Overrides ReadOnly Property RunningSpeed() As Integer
        Get
            Return Me._RunningSpeed
        End Get
    End Property

End Class

Public Class Dog : Inherits Animal

    Public Sub New()
        Me._RunningSpeed = 25
    End Sub

    Public Overrides ReadOnly Property RunningSpeed() As Integer
        Get
            Return Me._RunningSpeed
        End Get
    End Property

End Class

Now suppose we have a method called GetAnimalsRunningSpeed that looks like this:

Public Function GetAnimalsRunningSpeed( _ 
      ByVal SomeAnimal As Animal) As Integer
    Return SomeAnimal.RunningSpeed
End Function

There are two important observations to make here:
1. This function accepts a reference to an Animal object.
2. Since we declared the Animal class using the MustInherit keyword, we cannot create an instance of an Animal class.

So how do we call the GetAnimalsRunningSpeed if we cannot instantiate an Animal object? This is where polymorphism takes over.

You probably already know or heard that in VB.Net everything inherits from the Object class and therefore everything is an Object type. And you may also know that you can store anything in a variable that is declared as an Object. This holds true because the Object class is the ultimate base class for any other class created in VB.NET. So even if you create a class and don't inherit from any other class, you are still inheriting from the Object class because VB.NET will do this implicitly behind the scenes without requiring you to type the words "Inherits Object" in your class declaration. This means that the following two class declarations are the same:

Public Class classA
End Class

Public Class classA : Inherits Object
End Class

Why am I explaining all this?

In VB.NET, anywhere in a program that requires an instance of an Object variable, you can safely use an instance of any other class because, as I stated earlier, everything in VB.NET inherits from the object class and is an object, whether or not you explicitly inherit from the object class.

This rule extends to any class created in VB.NET.

In our example with the Animal class, anywhere that an Animal object is required, we can safely substitute an instance of a class that inherits from the Animal class. That means we can pass a Dog object or a Monkey object to the GetAnimalsRunningSpeed function because that function requires an Animal object, and the Dog object and Monkey object both inherit from the Animal class. The ability to use an object of a derived type anywhere an object of a base type is expected is what makes polymorphism possible.
The runtime doesn't care that the true type of the variable that is passed to GetAnimalsRunningSpeed is not an Animal object as long as it is an instance of a class that inherits from the Animal class. When the function is executed, then the runtime will examine the true type of the variable and call the RunningSpeed property that is defined in the class of the true type of the variable. That means if you call GetAnimalsRunningSpeed using a Monkey object like this:

Dim m As New Monkey
    MsgBox("The running speed of a monkey is " & _
      GetAnimalsRunningSpeed(m).ToString)

You will get a message box displaying the RunningSpeed value that is defined for the Monkey object.

If you call GetAnimalsRunningSpeed using a Dog object like this:

Dim d As New Dog
    MsgBox("The running speed of a dog is " & _
      GetAnimalsRunningSpeed(d).ToString)

You will get a message box displaying the RunningSpeed value that is defined for the Dog object. This happens even though GetAnimalsRunningSpeed expects an Animal object.

How all this relates to real life programming.

Inheritance based polymorphism seems cool and all that, by why would you want to use it in real life programming projects?

The answer is simple: It saves you lots of programming time and effort, makes your code neater and easier to understand, places critical sections of code in one spot, and makes it easier to incorporate changes and fixes.

In our example the GetAnimalsRunningSpeed function never has to change. Today it deals only with Monkey and Dog objects, but if you create other classes that inherit from the Animal class (perhaps a Cat class, a Horse class, etc.) you will never have to change the GetAnimalsRunningSpeed function to recognize those new classes. They inherit from the Animal class and therefore must have any public method declared in the Animal class. And that means an object instantiated from each of those classes can be seamlessly passed to the GetAnimalsRunningSpeed function.

Before object oriented languages became popular in software development, most programmers used languages that did not support polymorphism (most programmers did not even know what that meant!). A function such as GetAnimalsRunningSpeed would have to test for the kind of animal it was working with and would have to call the correct method based on that conditional statement. If a new animal were to be incorporated into this program, the GetAnimalsRunningSpeed function would have to be modified to test for that new animal so that it would know how to handle the call. This could get messy as more and more animals are added to the program (the animal kingdom is very large) and it makes it easy to introduce bugs into your program! Instead, using Inheritance and Polymorphism, each new derived class can contain all of the information necessary to perform the work for that specific type. This eliminates the need to make modifications to the base code and simplifies your coding efforts.

The examples in this article are trivial and designed for demonstration purposes only. In a real application the complexity level rises dramatically, and that is when you will realize the true power of inheritance based polymorphism.

For example, imagine a scientific research application that deals with formulas and with experiments and is designed to manipulate the settings of machinery during those experiments. Imagine that each experiment has different requirements and settings based on the material that is used in the experiment.

In that situation it may be possible for hundreds of different materials to be processed by an application.

One possible scenario here is to have a base class called Material with the methods for describing the necessary machinery settings when dealing with the material. Then you could derive classes from the Material class for each specific type of Material. In the derived classes you could include the necessary data that applies to that specific material. This means the actual code that manipulates the machinery during the experiment would not have to change each time a new material is introduced to the application. The chance for introducing errors into the application because of constant modification to the base code is eliminated since each new derived class can specify the new information that pertains to the new material without affecting any previous code!

Summary

The Overrides keyword, in conjunction with the Overridable and MustOverride keywords, is how VB.NET implements inheritance based polymorphism. The Overridable and the MustOverride keywords are used in a base class to designate methods that can be overriden. The Overrides keyword is used in a derived class when overriding one of those methods.

If you do not get familiar with the use of these keywords you will not be able to make use of the VB.NET mechanism for implementing this powerful concept into your programs. As a result, your applications may not be able to handle complex design problems efficiently and you may find yourself involved in programming maintenance activities and in bug fixes more than would otherwise be necessary.

You could avoid that by learning about polymorphism in VB.NET, familiarizing yourself with these keywords, and moving on up to the next level of programming skill in your career.

In the space of one article I could not cover everything that has to do with inheritance, polymorphism, and the related keywords. In fact, I've only scratched the surface. If you would like to read more, here are several links to additional information:

Using Inheritance in the .NET World, Part 1

Using Inheritance in the .NET World, Part 2

Inheritance And Override Lab

Polymorphism in VB.NET

In this installment we covered the Overrides keyword and other related keywords along with the concept of polymorphism. In the next installment we will tackle the Shadows keyword, discussing its purpose and how to use it. I'll see you then!

Advertisement

Missed an earlier article? You can now view back copies of the DevCity Newsletter on the devCity pages of the site.

Click Here

http://www.devcity.net/net/newsletters.aspx
Advertisement

We encourage you to pass this issue of
.net.devcity.weekly on to anyone you know with an interest in .NET technology and News You Can Compile

Manage Your Subscription Here.

You are currently subscribed as '*EMAIL*' to .net.devcity.weekly.

Click here to unsubscribe.

Thanks for reading!

Contact:
vbCity.com, LLC
4957 Lakemont Blvd SE C4 #331
Bellevue, WA 98006


DevCity.NET is hosted by FullControl.NET

Copyright vbCity.com, LLC 2003. All Rights Reserved.