Answer to Question #50514 in Visual Basic for Bender

Question #50514
What is an overloaded method and why are these useful? Illustrate your answer with an example of when you would do this.
Expert's answer
What is an overloaded method and why are theseuseful? Illustrate your answer with an example of when you would do this.

If you wanted to create a group of functionsthat each did essentially the same thing, with only their parameters changed, You
can using optional parameters, or bychanging the name of the function. Both techniques work, but they are not very
elegant. In Visual Basic you are allowed to create methods in a class that have
the same name but different argument lists, VB figure out which method to call
during compile based on the parameter types that you pass. This technique is
called overloading a method. The benefit of using the same name is thatthe user interface is kept consistent; only the inputs are different. The
functionality within the method changes for each new overloaded method.
For example, you want wrote function which willpass in a number representing the position of the word you wish to retrieve
from the line, or for search string and the method will return the first word
in the line of text that contains that string. You create two more versions of
this GetWord method.
The signature of a method consists ofits name, parameters, and return type—in other words, the arguments that
differentiate one "flavor" of the method from another. The signatures
for these three methods look like the following lines of code:
Function GetWord() As StringFunction GetWord(ByVal Position As Integer) As StringFunction GetWord(ByVal Search As String) As StringThe name of the method (GetWord)stays the same in each of the above methods, but the argument list is different
for each one. The compiler can resolve each of these names based on these
different "signatures." Notice that the return value is the same for
each method. Keeping the return value the same is not a requirement, but you
normally will not change the return value on overloaded methods. Changing only
the return type on a method does not overload a method. If you try to do this,
Visual Basic .NET gives you an error message telling you that you cannot
overload a method by changing the return type. You must change at least one
argument for a method to have a different signature and be overloaded.
Overloading a method allows you tokeep your interface consistent, and allows you to logically call the same
method regardless of the types of data you are passing in. You will find that
using the same name will help you remember what a procedure does, as opposed to
having to come up with new names or a naming convention, to help you keep
things straight.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be the first!

Leave a comment

Ask Your question

New on Blog