+ All Categories
Home > Documents > Visual Basic Tutorial Chapter 1

Visual Basic Tutorial Chapter 1

Date post: 07-Apr-2018
Category:
Upload: shoebie
View: 225 times
Download: 0 times
Share this document with a friend

of 20

Transcript
  • 8/4/2019 Visual Basic Tutorial Chapter 1

    1/20

    1. Getting StartedIn this book, we work under the basic assumption that you have no inkling about any of theprogramming languages, and VisualBasic.Net in particular. But, you would invariably haveheard people fantasizing about the great new product called Visual Studio.Net, which is in thereckoning to bring about a revolution in the software industry.

    So, let us get to the meat of this product. We shall gain a meticulous understanding of thislanguage and its features, and only then shall we decide whether the claims made by thepopulace are justified or not. We could keep extolling the virtues of the finer things in life, butwe'd rather get down to brass-tacks straightaway. We assume that you have a copy of VisualStudio.Net installed on your machine.

    To launch Visual Studio, click on the ubiquitous Start Button in Windows. (In our case, wehave installed Windows 2000). Then, click on Programs, followed by Microsoft Visual Studio.Net. Finally, select the option of Microsoft Visual Studio .Net. This is shown in the Screen 1.1.

    Screen 1.1

    Shortly thereafter, a window pops up, showing Visual Studio.Net in all its glory, as shown in

    screen 1.2.

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    2/20

    Screen 1.2

    Hey, hang on! Could there be something amiss with what you are doing? Your copy of VisualStudio .Net could be displaying something totally different!! Yes, this could be a distinctpossibility!

    One of the salient features of present day software is that it can be customized to a largeextent. This is why the final appearance of a product could be drastically different from what itoriginally looked like, when freshly taken out of the box. Thus, the screen 1.2 will never lookidentical on all the machines. We shall explicate these differences in due course, but for themoment, we are exceedingly inclined towards embarking upon the development of a smallapplication or project. But before venturing any further, close all the child windows by clickingon the x sign.

    Then, click on the menu option File, followed by New, and finally Project. This becomes evidentin screen 1.3.

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    3/20

    Screen 1.3

    The above actions will result in the display of the Dialog box titled "New Project". This is shownin screen 1.4.

    The advantage of using Visual Studio .Net is that diverse applications, each using a differentprogramming language, can be developed simultaneous, under a single streamer.

    This explains why three language options are present in the first pane of the dialog box, viz.Visual Basic, Visual C# and Visual C++.

    Screen 1.4

    The option of Visual Basic project is listed first. Hence, it is highlighted by default. Thissignifies the priorities of Microsoft, and is the very raison de etr of this book!

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    4/20

    A perfect analogy for Visual Studio .Net is that of a glass, which can be used to drink eitherwater or juice or wine. In a similar fashion, under the single roof of Visual Studio .Net, variousprograms developed in different languages, can be written. The language used is simply not anissue.

    The second pane titled 'Templates' determines the type of application that would eventually be

    created. This could be an executable file running under Windows, or a Web Applicationrunning a web server.

    Since we are nave about this product, we select the option of Windows Application. This optionis selected by default.

    The next task is to specify a name for the project. We have chosen the name 'vvv', since wesincerely believe that it will bring us good tidings on our very first application. We have usedour newly created folder called 'v1' as the location for creating the application. You are atliberty to choose any folder that you fancy.

    Screen 1.5

    After specifying all the details as shown in screen 1.5, click on the OK button.

    This brings us to Screen 1.6, where we encounter an empty form.

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    5/20

    Screen 1.6

    Now, in order to view the output of our handiwork, click on the menu option Debug, and thenon Start. This is shown in screen 1.7.

    Screen 1.7

    This ignites the excitement of Visual Studio .Net, and it starts processing the request. Finally,as the outcome of the operation, it displays an empty form, as seen in screen 1.8. This is nomean achievement for people like us, considering the fact that we have not written even asingle line of code yet!

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    6/20

    Screen 1.8

    Close this form window by clicking on the x sign on the right hand side. This will revert usback to the form in Visual Studio .Net. The next task that we venture upon is, to display abutton on the form. To accomplish this, click on the menu option View, and then, on the optionof ToolBox, as shown in screen 1.9.

    Screen 1.9

    This option brings up a toolbox containing a list of objects or controls. The toolbox window isvisible on the left hand side of the screen, as revealed in screen 1.10.

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    7/20

    Screen 1.10

    Now, simply click on the control labelled as Button to select it, and then, drag and drop it intothe form. Screen 1.11 displays the position where we have dropped our button.

    Screen 1.11

    Then, run the application in the customary manner by clicking on the menu Debug, and then,click on Start. Screen 1.12 confirms that the form now contains the button in it. Pat on theback! Having covered just a couple of pages, we have already placed a button on the form.

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    8/20

    Screen 1.12

    The shortcoming of our present endeavour is that, we are clueless about what is going onbehind the scenes. Clicking on the OK button in the New Project dialog box, results in thegeneration of considerable amount of code by the Visual Studio .Net framework. Apparently, wehave merely clicked on the ToolBox, which is a User Interface tool; and then, we have draggedand dropped a button in the form. However, in reality, ample code has been generated in thebackground to accomplish this seemingly simple task.

    We are convinced that prior to forging ahead with the task of building complex applicationsusing Visual Studio .Net, there is a need for discerning the code that it generates. Also, alongthe way, we shall keep reverting back to the Visual Studio .Net framework, to demonstrate asto how it has made a programmer's life more easygoing. However, you have to learn a

    programming language that is to be used with it, since it is a fundamental fact that VisualStudio .Net cannot build customized applications by itself. It is the task of the programmer toprogram it to satisfy the specific requirements.

    So, we start by writing the smallest Visual Basic program. As is customary in all our books, weshall refrain from attempting to impress you with our knowledge of programming. Instead, weshall proceed systematically, a single step at a time. So, here we go!

    First, create a folder named il on your hard disk. Then, using a text editor such as Notepad,create a file called a.vb, with the following contents in it:

    a.vbModule zzz

    End Module

    To execute the above code, go to the Visual Studio .NET Command Prompt (Start-> Program->Visual Studio .Net-> Visual Studio .Net Tools-> Visual Studio .NET Command Prompt), and runa program called vbc. We achieve it as follows:

    c:\il>vbc a.vb

    This action of ours results in the following error message:

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    9/20

    vbc : error BC30420: 'Sub Main' was not found in 'a'.

    Every Visual Basic program must be enclosed within the words 'Module' and 'End Module'.There is no rational explanation for this prerequisite. So, we accept it as the dictum. EveryModule requires a name. So, we have chosen the name 'zzz'. This name has been deliberately

    chosen to demonstrate that the name per se, is not very significant. Any name would suffice, aslong as one is present. An empty module is forbidden. Further, the error message displayedearlier clearly mandates the presence of a function or a sub-routine called Main.

    a.vbModule zzzSub Main()End SubEnd Module

    After we insert two lines within the Module, the compiler successfully compiles without anyhiccups. In the directory, you will see a file called a.exe, which when executed, does not displayanything.

    Visual Basic is a case-insensitive language. However, we still follow the Microsoft convention ofwriting the word Module with a capital M, even though we are at liberty to determine our owncapitalization rules.

    After having attended to the first rule of Visual Basic, i.e. enclosing the code within the words'Module' and 'End Module', we progress onto the second rule, which insists on the presence ofa sub-routine called Main. The word 'sub' is a short form for the term sub-routine, which takesa name along with it. It is merely a collection of code.

    A sub-routine is created in a manner similar to the creation of a module, where we begin withthe word Sub, followed by the name of the sub-routine, i.e. Main. Finally, the subroutine has toconclude with the word 'End', followed by the word 'Sub'. A 'Sub' can have a pair of open and

    close brackets. However, they are optional. So, on odd days we write 'Sub' with brackets in ourprograms, while on even days, we omit them ;-).

    The Visual Basic language is verbose and rather lax in its rules. Now, let us write a programthat displays a string.

    a.vbModule zzzSub Main()System.Console.WriteLine ("Hello")End SubEnd Module

    Output

    Hello

    On compiling and executing the above program, we are greeted by the word "Hello" in theoutput. It has been an ancient programming tradition wherein, the first program in anyprogramming language displays the word "Hello". The word "Hello" gets displayed on the screenbecause a function has been executed or called.

    In a programming language, a function name constitutes a word, followed by a pair of roundbrackets.

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    10/20

    Thus, Main is a function, since it ends with a pair of round brackets. However, there is a subtledifference, which is:

    In the case of Main, we were creating a function or a sub-routine, since the line startedwith the word 'Sub'. In the case of System.Console.WriteLine ("Hello"), the word 'Sub' is not present. Hence,

    it construes that a function or subroutine is being called for execution.

    There is a minor distinction between a subroutine and a function, which we shall attend tolater on, in the chapter.

    The name of our function i.e. System.WriteLine.Console, is considerably long. We need nottorment ourselves about the details of how this function has been written, at this stage. Weonly have to be conscious of the fact that it requires some words to be inserted within doublequotes, which it will display on the screen.

    Since we have specified the word Hello within double quotes, the console displays the word"Hello". This is the mechanism of passing data or parameters to a function. This function is oneof the innumerable ones that are available in Visual Basic. We can use them on multiple

    occasions in our code.

    a.vbModule zzzSub MainSystem.Console.WriteLine ("Hello")System.Console.WriteLine (100)End SubEnd Module

    OutputHello100

    A single function is capable of embodying multiple lines of code. In the above program, we havecalled the function System.Console.WriteLine twice: On the first occasion, we have passed a string or a sequence of letters of the alphabet as

    a parameter. On the second occasion, we have passed it a number.

    The function dutifully prints out both the values without complaining at all.

    a.vbModule zzzSub MainSystem.Console.WriteLine (vijay)End SubEnd Module

    Errorc:\il\a.vb(3) : error BC30451: Name 'vijay' is not declared.System.Console.WriteLine (vijay)

    In the WriteLine function, we have specified the word vijay, without enclosing it within invertedcommas. The Visual Basic product or compiler reverts back with an error, expressing itsignorance about the name vijay. It expects it to be declared explicitly.

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    11/20

    a.vbModule zzzSub Maindim vijayvijay = 100System.Console.WriteLine (vijay)End SubEnd Module

    Output100

    To create or declare any valid name, the line must begin with the word DIM, followed by thename, thereby, informing VisualBasic.Netthat a name is being created. Thus, 'DIM vijay'signifies that the name vijay is being declared. These names are created so that they can storevalues in them. On the next line, we have specified a value of 100 to be stored in the namevijay.

    An elementary rule in all programming languages is that, a number or a string may besubstituted by a name that holds the value. Therefore, when the function WriteLine isfurnished with the name vijay, no error is generated. This is because, the framework firstidentifies the value contained in it. Since vijay holds the value of 100, it is displayed on thescreen.

    a.vbModule zzzSub Maindim vijayvijay = 100System.Console.WriteLine (vijay)vijay = 200System.Console.WriteLine (vijay)vijay = vijay + 10System.Console.WriteLine (vijay)vijay = vijay + 1System.Console.WriteLine (vijay)End SubEnd Module

    Output100

    200210

    211

    As was done in the program above, we create a name vijay and assign it a value of 100. Then,using the WriteLine function, the value is displayed. vijay is then re-assigned a new value of200, which is also displayed. Thus, the value stored in vijay can vary. Due to this ability tohold varying values, words such as vijay, are termed as variables.

    On the next line, we have performed an arithmetic operation by presenting the statement vijay= vijay + 10. On encountering a line containing an 'equal to' sign =, initially all attention isriveted on the expression that is on the right side of the sign. This expression is 'vijay + 10'. So

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    12/20

    firstly, the value of vijay is evaluated to obtain a value of 200. Then, 10 is added to it, in orderto obtain a result of 210.

    This value is now assigned to the variable on the left hand side of the 'equal to' sign, i.e. vijay,thereby updating its value. Thus, when the variable vijay is displayed, it shows the value of210. In the next round, the value of the variable is increased by 1, thus, making the final value

    as 211.

    The concept of variables is one of the pillars on which the programming world rests. Here, aword or name holds a value, which can keep fluctuating.

    a.vbModule zzzSub Maindim vijayvijay = 100System.Console.WriteLine (vijay)vijay = "hi"System.Console.WriteLine (vijay)End SubEnd Module

    Output100

    hi

    In this example, the variable vijay is first assigned a numeric value 100. Then, it is assigned astring value of "hi". Nobody complains and both values get displayed. Thus, we have the licenseto change the data type of the value that the variable can hold.

    a.vbModule zzzSub Maindim vijay as integervijay = 100System.Console.WriteLine (vijay)vijay = "hi"System.Console.WriteLine (vijay)End SubEnd Module

    Output100

    Unhandled Exception: System.InvalidCastException: Cast from string "hi" to type 'Integer' is not valid. --->System.FormatException: Input string was not in a correct format.

    at Microsoft.VisualBasic.CompilerServices.DoubleType.Parse(String Value, NumberFormatInfoNumberFormat)

    at Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value)--- End of inner exception stack trace ---at Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value)at zzz.Main()

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    13/20

    The previous program does not demonstrate the conventional technique of programming,because a variable must essentially represent only a single type during its lifetime. To maintainabsolute consistency, the data type is specified while creating the variable.

    This is achieved by adding the word 'as' after the DIM variable, followed by a predefined datatype. vijay is assigned the data type of integer, which implies that the variable vijay shall store

    only numbers or integers.

    After displaying the number that it contains, the variable vijay is then initialized to a stringvalue of "hi". The earlier program had not protested under similar circumstances.However, now we come across a mammoth dialog box displaying an error message. When weclick on No, we observe the above error on the console.

    This error or exception enucleates the fact that, we are not empowered to specify a string valuefor a variable that has been declared to be of type integer. Henceforth, we shall declare all ourvariables with a data type.

    a.vbModule zzzSub Maindim i,j as integeri = 10System.Console.WriteLine ("{0} {1}", i, j)End SubEnd Module

    Output10 0

    In a single stroke, we have the ability to create as many variables as we wish, separating eachone of them with a comma. The above example has two integer variables named i and j, whichhave been declared together. The variable i is assigned a value of 10, while j is not initialized at

    all. In the same manner that was used to create two variables simultaneously, we now wish toprint their values too in a single stroke.

    To accomplish this, the WriteLine function has been modified and assigned a string that hasthe numbers 0 and 1 enclosed within curly braces. This string parameter is followed by the twovariables i and j, separated by commas. They are extra parameters.

    The WriteLine function replaces the first curly brace of 0, with the value of the first parameterafter the string i.e. i, and the second curly braces of 1 with the second parameter after thestring, i.e. j. Since the value of the variable i is 10, and the value of the variable j is 0, theoutput that is displayed is 10 0. Thus, not only have we learnt how to print multiple variablesusing a single WriteLine function, but have also become wiser by the fact that, if a variable isnot assigned a value, it obtains a default value of 0.

    a.vbModule zzzSub Maindim b as booleandim i as integerdim j as stringj = "hi"i = 10b = true

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    14/20

    System.Console.WriteLine ("{0} {1} {2} {3}" , i > 20 , i < 20 , b , j = "hi")End SubEnd Module

    OutputFalse True True True

    A data type represents a specific type of data. In the above example, we have created threetypes of variables:

    i is of type integer j is of type string b is of type Boolean.

    A Boolean type can store only one of the two values, true or false.

    The variable i of type integer can hold any valid number. It is assigned the value of 10.

    The variable j, of type string, must have its value enclosed within double inverted commas. It isassigned a value of "hi".

    The boolean variable b is initialized to a value of true.

    In the WriteLine function following the string, we first display the expression i > 20, instead ofthe variables. Doing so, indirectly poses the question "Is the variable i greater than 20?"

    The result can either be true or false. Since the value of the variable i is 10, which is less than20, the value of False is displayed. The second expression determines whether the value of i isless than 20 or otherwise. Since this is affirmative, the value of True is displayed on the screen.

    The third parameter to the WriteLine function simply displays the value of the boolean variableb. The value of the boolean variable is not altered from what it was initialized to. Hence, theoutput is displayed as True.

    The last check performed is, whether the value of the string j is equal to the string value "hi" ornot. Since they both are the same, the resultant value of True is displayed. Thus, all the aboveexpressions result in a boolean value of either true or false.

    a.vbModule zzzSub Maindim i as integeri = 10if i > 50 thenSystem.Console.WriteLine ("Condition True")End ifif i > 5 thenSystem.Console.WriteLine ("Second Condition True")End ifEnd SubEnd Module

    OutputSecond Condition True

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    15/20

    The programs that we have presented so far are absolutely straightforward, since every line ofcode that is entered, gets called sequentially. We desire to execute code based on certaincircumstances.

    The above program is the perfect prescription for this. We have created an integer i with a valueof 10. Then, we encounter an 'if' statement.

    An 'if' statement is always followed by a condition or an expression, and the line ends with a'then'. In the first case, a check is performed to determine whether the value of the variable i islarger than 50 or not. Since the answer is False, all the lines of code leading up to the 'End If',are ignored. Thus, the first WriteLine function with the Condition True, does not get executedat all.

    The condition with the second 'if' statement, verifies whether the value of i is greater than 5 ornot. Since it is, all the code between the 'if' and the 'end if' is executed. Thus, an 'if' statementis used to make decisions, i.e. to intelligently execute specific code, depending upon whethersome variables have certain values or not. In this manner, we can effortlessly write intelligentand dynamic programs.

    a.vbModule zzzSub Maindim i as integeri = 10if i > 50 thenSystem.Console.WriteLine ("Condition True")elseSystem.Console.WriteLine ("Condition False")End ifif i > 5 thenSystem.Console.WriteLine ("Second Condition True")End ifEnd SubEnd Module

    OutputCondition FalseSecond Condition True

    In the above program, the 'if' statement now has the 'else' clause added to it. In the earlierprogram, when the result of the 'if' statement was false, no code was executed.Now, since the 'else' clause has been added, whenever the 'if' statement is false, the statementswithin the 'else' block are executed. So, all code from the 'else' upto the 'end if', is executed.When the 'if' condition results in True, the statements contained within the 'if' upto the 'else',are executed.

    The advantage of using the 'else' clause is that, some code finally gets executed. However, the'else' clause is optional.

    Subroutines

    a.vbModule zzzSub Mainabc

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    16/20

    End SubEnd Module

    Errorc:\il\a.vb(3) : error BC30451: Name 'abc' is not declared.

    By introducing the name abc, we have attempted to call a subroutine or a function by thatname. Like before, an error is generated, since abc has not been declared. Thus, as in the caseof variables, we have to declare or create the subroutine or function before calling our owncode.

    a.vbModule zzzSub MainabcEnd Subsub abcSystem.Console.WriteLine("in abc")end subEnd Module

    Outputin abc

    At the very outset, we had created a subroutine called Main, by using Sub. Harnessing thesame mechanism, we now create another subroutine called abc.

    The only difference between the two sub-routines is that the code in Sub Main is called whenthe .exe file is executed, whereas, the code in the other subroutines has to be called explicitly.

    To execute code in a subroutine, just the name of the subroutine has to be specified on a blankline. Hence, we have merely specified the name abc. This action calls the code in the

    subroutine, thereby resulting in the WriteLine function being called, with the string 'in abc'.This sounds too easy to be true!

    a.vbModule zzzSub MainabcpqrEnd Subsub abcSystem.Console.WriteLine("in abc")pqr()pqrend subsub pqrSystem.Console.WriteLine("in pqr")end subEnd Module

    Outputin abcin pqrin pqr

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    17/20

    in pqr

    We can create as many subroutines or subs as we like in a single module. The above programdisplays two subroutines, both of which are called from the Main block. Furthermore, the pqrsubroutine is called twice from the abc subroutine.

    Thus, we enjoy the privilege of calling code contained in any other subroutines, as many times

    as we desire. You would notice that at one stage we had called the pqr subroutine, using theopen and close brackets. The brackets are optional. So, their presence or the lack of it, doesnot interfere much with the execution of the code.

    a.vbModule zzzSub Mainabc("Hi")End Subsub abc()System.Console.WriteLine("hell")end subEnd Module

    c:\il\a.vb(3) : error BC30057: Too many arguments to 'Public Sub abc()'.

    In the above example, an error is generated, since we are passing the string parameter "Hi" tothe sub abc; whereas, the sub abc has not been declared to accept any parameters. So, let usrectify this situation in the subsequent example.

    a.vbModule zzzSub Mainabc("Hi")End Subsub abc(s as string)System.Console.WriteLine(s)end subEnd Module

    OutputHi

    The above example demonstrates the correct way of creating a subroutine. The string "hi" ispassed as the value for the variable 's' in the sub abc. The variable 's' is termed as a parameter.It is supplied to the WriteLine function for display purposes. Subroutines that acceptparameters are very practical and efficacious, since they infuse a lot of flexibility and generalityinto the program.

    a.vbModule zzzSub MainDim s,t,u as strings = "hi"t = "bye"u = "No"abc(s,t,u)System.Console.WriteLine("{0} {1} {2}",s,t,u)End Sub

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    18/20

    sub abc(s0 as string , byval s1 as string, byref t1 as string)System.Console.WriteLine("{0} {1} {2}",s0,s1,t1)s0 = "good"s1 = "bad"t1 = "ugly"end subEnd Module

    Outputhi bye Nohi bye ugly

    In the above example, there are three string variables viz. s, t and u. They are initialized to "Hi","Bye" and "No", respectively. These three variables are then furnished as parameters to thesubroutine abc.

    In the Sub, the values passed by the three variables, are stored in the parameters s0, s1 andt1. We will explore the other parameter details in a short while.

    Thereafter, the three values are displayed using the WriteLine function. Then, the values of theparameters s0, s1 and t1 are modified to some other values. Once the subroutine abc ends, thecontrol moves on to the next line in the Main block.

    Here, we again use the WriteLine function to display the values of the variables s, t and u. Toour utter astonishment, we discover that the value of the variable 'u' is different from what ithad been initialized to. It displays the new value that has been assigned to it in the abcsubroutine. However, s and t retain their old values.

    In sub abc, we have changed the values of the parameters, and not the original variables.Notwithstanding this, the value contained in the variable 'u' within the main subroutine,changes. This is because of the fact that, we have affixed the word 'byref' before the name ofthe parameter. This word signifies that if the parameter t1 changes in the sub abc, the original

    variable in the calling Sub would also change correspondingly.

    By using the word 'byval', any changes made to the value of the variable in the subroutine,would not percolate down to the original variable.

    The default is 'byval', and since it has not been mentioned for the first parameter, the effect isthat of byval. Thus, it is the sub that decides on whether to reflect the changes made, onto theoriginal variable that is passed as a parameter.

    a.vbModule zzzSub MainDim s as strings = "hi"abc()End Subsub abc()s = "No"end subEnd Module

    Errorc:\il\a.vb(8) : error BC30451: Name 's' is not declared.

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    19/20

    We did not enlighten you earlier about a very essential feature of Sub. However, this seems tobe an opportune time to divulge the fact that, a Sub is an independent and a self-containedentity. The variable 's' created in the sub main, is not discernible in the sub abc. Hence, thecompiler generates the above error.

    a.vbModule zzzSub MainDim s as integers = abc(10,20)System.Console.WriteLine(s)End SubFunction abc(i as integer , j as integer) as integerabc = i + jend FunctionEnd Module

    Output

    30

    Your reaction to this book could range from being extremely positive to being outright negativeand unimpressed. This would depend upon how well you relate to our style. It has always beenour endeavour to explain only a single concept at a time. This could get exasperating for a largenumber of people.

    The above example highlights the difference between a sub and a function. They are almostidentical, but for one variation, i.e. a function can return a value, whereas, a Sub cannot.

    In many situations, returning values is very important because functions normally performcertain tasks and return the result of their operation. The above function abc accepts twointegers parameters and returns their sum.

    Creating functions is a child's play, since it entails replacement of the word 'Sub' with the word'Function' and the words 'End Sub' with the words 'End Function'. The words 'as Integer'signify that the function will return an integer when it is called. To return a value in a function,the name of the function has to be initialized to the specific value. Thus, writing abc=100 willreturn 100.In our case, we are adding up the two parameters 10 and 20, and initializing the functionname abc with the sum of 30. Thus, the variable s in the sub main will now have a value of 30,which is the return value of the Function.

    a.vbModule zzzSub MainDim s as integers = abc(10,20)abc(100,300)System.Console.WriteLine(s)End SubFunction abc(i as integer , j as integer) as integerabc = 300abc = i + jend FunctionEnd Module

  • 8/4/2019 Visual Basic Tutorial Chapter 1

    20/20

    Output30

    You may set the return value as many times as you like. No one would whine. The last value tobe returned will be the one that is finally used. Thus, the return value of 300 is overridden by

    the last value to be returned, i.e. 30.

    Even though it is the job of a function to return a value, we can avoid storing the return valuein a variable. Thus, in the second round, when the function abc is called, we do not save itsreturn value in a variable. However, nobody makes a fuss about it.

    As has been oft repeated by us, VisualBasic.Netis a very forgiving and flexible language, andthat is precisely why we love it as much as we do!


Recommended