Theme index -- Keyboard shortcut: 'u'  Previous theme in this lecture -- Keyboard shortcut: 'p'  Next slide in this lecture -- Keyboard shortcut: 'n'Introduction to C#

A complete PDF version of the text book is now available. The PDF version is an almost complete subset of the HTML version (where only a few, long program listings have been removed). See here.

8.  C# in relation to Visual Basic

This chapter is intended for students who have a background in imperative Visual Basic programming. The goal of this chapter is to make the transfer from Visual Basic to C# as easy as possible. We do that by showing and discussing a number of equivalent Visual Basic and C# programs. In this chapter Visual Basic programs are shown on a blue background, and C# programs are shown on a green background. The discussion of equivalent Visual Basic and C# program is textually organized in between the two programs.

In this chapter 'Visual Basic' refers to the version of Visual Basic supported by the .Net Framework version 2.0.

In this edition the comparison of Visual Basic and C# is only available in the web version of the material.

8.1 The Overall Picture8.5 Control Structures for Iteration
8.2 Declarations and Types8.6 Arrays
8.3 Expressions and Operators8.7 Procedures and Functions
8.4 Control Structures for Selection
 

8.1.  The Overall Picture
Contents   Up Previous Next   Slide Annotated slide Aggregated slides    Subject index Program index Exercise index 

We will start with a program almost at the 'Hello World' level.

1
2
3
4
5
6
7
8
9
Module MyModule

    Sub Main()
        Dim name As String   ' A variable name of type string
        name = InputBox("Type your name")
        MsgBox("Hi, your name is " & name)
    End Sub

End Module
Program 8.1    Typical overall program structure of a Visual Basic Program.

In the Visual Basic program we have a Main procedure (subprogram) within a module called MyModule. A Visual Basic module is similar to a class (in C# and Visual Basic) of which we only have a single instance. In line 4 we declare a string variable called name. We read string via a InputBox and we show a message through af message box.

In the C# program below we have a similar Main method which does textual input/output with use of WriteLine and ReadLine methods in the Console class. As we will see in a moment, these methods can be used in exactly the same way in Visual Basic, because Visual Basic and C# share the Console class and other .NET libraries.

In both programs we could have used a namespace construct at the outer level, see Section 15.1. In this chapter - as well as in many other parts of this material - we disregard namespaces.

1
2
3
4
5
6
7
8
9
10
11
12
using System;

class SomeClass{

  public static void Main(){
    string name;    // A variable name of type string
    Console.WriteLine("Type your name");
    name = Console.ReadLine();
    Console.WriteLine("Hi, your name is " + name);
  }

}
Program 8.2    Typical overall program structure of a C# Program.

We can summarize the overall similarities and differences between Visual Basic and C# in the following way:

  • Program organization

    • Similar: Modul/Class in explicit or implicit namespace

  • Program start

    • Similar: Main

  • Separation of program parts

    • VB: Via line organization

    • C#: Via use of semicolons

  • Comments

    • VB: From an apostrophe to the end of the line

    • C#: From // to the end of the line or /* ... */

  • Case sensitiveness

    • VB: Case insensitive. You are free to make your own "case choices".

    • C#: Case sensitive. You must use the correct case for both keywords and you must be "case consistent" with respect to names.

Notice in particular that line breaks at particular places are very important in Visual Basic, but not at all important in C# (and most other programming languages). In C# and many other similar languages, we use semicolons after commands, and after many other program units. Notice also that C# is case sensitive. The variables name and Name designate two different names in C#, but one and the same name in Visual Basic.

 

8.2.  Declarations and Types
Contents   Up Previous Next   Slide Annotated slide Aggregated slides    Subject index Program index Exercise index 

We will now take a look at variable declarations and types.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Option Strict On
Option Explicit On

Module DeclarationsDemo

    Sub Main()
        Dim ch As Char = "A"C     ' A character variable
        Dim b As Boolean = True   ' A boolean variable
        Dim i As Integer = 5      ' An integer variable (4 bytes)
        Dim s As Single = 5.5F    ' A floating point number (4 bytes)
        Dim d As Double = 5.5     ' A floating point number (8 bytes)
    End Sub

End Module
Program 8.3    A Visual Basic Program with a number of variable declarations.

In the C# program below we declare a number of variables from line 6-10. Similar variables are declared in line 7-11 of the Visual Basic program above.

In a C# declaration, the type comes before the variable. In Visual Basic the order is the opposite. In addition, Visual Basic uses the Dim and As keywords. In C# there are no keywords involved.

The two programming languages use different names for similar types. In C#, the Visual Basic type Single is called float. All built-in types in C# start with a lower case letter.

1
2
3
4
5
6
7
8
9
10
11
12
13
using System;

class DeclarationsDemo{

  public static void Main(){
    char ch = 'A';          // A character variable
    bool b = true;          // A boolean variable
    int i = 5;              // An integer variable (4 byges)
    float s = 5.5F;         // A floating point number (4 bytes)
    double d = 5.5 ;        // A floating point number (8 bytes) 
  }

}
Program 8.4    The similar C# program with a number of variable declarations.

We summarize declarations and types in the following way:

  • Declaration structure

    • VB: Variable before type

    • C#: Variable after type

  • Types provide by the languages

    • The same underlying types

    • Known under slightly different names in VB and C#

 

8.3.  Expressions and Operators
Contents   Up Previous Next   Slide Annotated slide Aggregated slides    Subject index Program index Exercise index 

Below we show three Visual Basic programs and three similar C# programs with the purpose of illustrating aspects of expressions and operators. Expressions typically make use of operators. Expressions are evaluated to find their values. We do not normally expect other things to happen when we evaluate an expression.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Option Strict On
Option Explicit On

Module ExpressionsDemo

    Sub Main()
        Dim i as Integer = 13 \ 6       ' i becomes 2
        Dim r as Integer = 13 Mod 6     ' r becomes 1
        Dim d as Double = 13 / 6        ' d becomes 2,16666666666667
        Dim p as Double = 2 ^ 10        ' p becomes 1024

'       Dim b as Boolean i = 3          ' Illegal - Compiler error
        Dim b as Boolean, c as Boolean  ' b and c are false (default values)
        c = b = true                    ' TRICKY: c becomes false 
    End Sub

End Module
Program 8.5    A Visual Basic Program with expressions and operators.

In C# the meaning of the operator / depends on the types of the operands. If both i and j are integers, i / j is integer division. Visual Basic uses the operator symbol \ (back slash) for integer division.

In C# the operator % is used to find the remainder of an integer division. In Visual Basic, the similar operator is Mod.

Line 12 of the Visual Basic program is erroneous, and therefore preceded by a comment symbol (and as such excluded from the program). The idea is to assign the value of i = 3 (which is true or false) to the boolean variable b. This confuses Visual Basic! The similar expression in C# (line 10) works as expected. In C# the operator == is the equality operator and = is assignment (which also is an operator in C#). The value of the C# expression var = expr is the value of expr.

In the Visual Basic expression c = b = true the leftmost equality is assignment and the rightmost equality is equality. Thus, to c we assign whether b is equal to true. It is not. In the similar C# expression in line 11 both equality symbols are assignment operators. In C# c = b = true means c = (b = true). Thus, b is first assigned to true. Next c is assigned to the value of the expression b = true, which is true. We can also say that, in C#, c = b = true has the same effect as the two statements b = true; c = true. Thus, true is assigned to both b and c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
class ExpressionsDemo{

  public static void Main(){
    int i = 13 / 6;             // i becomes 2
    int r = 13 % 6;             // r becomes 1
    double d = 13.0 / 6;        // d becomes 2.16666666666667
    double p = Math.Pow(2,10);  // p becomes 1024

    bool b = i == 3;            // b becomes false
    bool c = b = true;          // both b and c become true
  }

}
Program 8.6    The similar C# program with a number of expressions and operators.

In the following we illustrate the operators is different from and logical negation in both Visual Basic and C#. In relation to Visual Basic it is most natural to do so in the context of an if-then-else statement, see also Section 8.4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Option Strict On
Option Explicit On

Module ExpressionsDemo

    Sub Main()
        Dim i as Integer = 2, r as Integer = 1

        If i <> 3 Then
          Console.WriteLine("OK")    ' Writes OK
        End If               

        If Not i = 3 Then
          Console.WriteLine("OK")    ' Same as above
        End If  
    End Sub

End Module
Program 8.7    A Visual Basic Program with expressions and operators.

In line 7 of the C# program shown below, the expression i != 3 is similar to the Visual Basic expression Visual Basic i <> 3. It means is i different from 3. When i is 2, the value of i != 3 is true.

In line 8 of the C# program, the expression !(i == 3) is equivalent to i != 3. The parentheses in !(i == 3) are necessary. !i == 3 means !(i) == 3 which does not make sense. The reason is that the operator ! has has higher priority than the operator == in C#, see Section 6.7.

1
2
3
4
5
6
7
8
9
10
11
using System;
class ExpressionsDemo{

  public static void Main(){
    int i = 2, r = 1;

    if (i != 3) Console.WriteLine("OK");       // Writes OK
    if (!(i == 3)) Console.WriteLine("OK");    // Same as above
  }

}
Program 8.8    The similar C# program with a number of expressions and operators.

In the following two programs we illustrate short circuited boolean operators.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Option Strict On
Option Explicit On

Module ExpressionsDemo

    Sub Main()
        Dim i as Integer = 2, r as Integer = 1

        If i = 3 AndAlso r = 1  Then   ' Writes OK
          Console.WriteLine("Wrong") 
        Else 
          Console.WriteLine("OK") 
        End If  

        If i = 3 OrElse r = 1  Then   ' Writes OK
          Console.WriteLine("OK") 
        Else 
          Console.WriteLine("Wrong") 
        End If  
    End Sub
End Module
Program 8.9    A Visual Basic Program with expressions and operators.

The C# expression i == 3 && r == 1 tests if i is equal to 3 and r is equal to 1. The value of i == 3 is false, and therefore the expression r == 1 is not evaluated; The expression r == 1 does not affect the value of the overall expression. This is the idea behind short circuited operators. In line 12 we illustrate the similar short circuited or operator ||.

In Visual Basic AndAlso corresponds to && and OrElse corresponds to ||. Visual Basic also has non-short circuited boolean operators And and Or. In C#, & and | are bitwise logical operators, and as such they are not equivalent to And and Or in Visual Basic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
class ExpressionsDemo{

  public static void Main(){
    int i = 2, r = 1;

    if (i == 3 && r == 1)
      Console.WriteLine("Wrong");
    else
      Console.WriteLine("OK");

    if (i == 3 || r == 1)
      Console.WriteLine("OK");
    else
      Console.WriteLine("Wrong");
  }
}
Program 8.10    The similar C# program with a number of expressions and operators.

We emphasize the following aspects of expressions and operators:

  • Operator Precedence

    • Major differences between the two languages

  • Equality and Assignment

    • VB: Suffers from the choice of using the same operator symbol = for both equality and assignment

    • VB: The context determines the meaning of the operator symbol =

    • C#: Separate equality operator == and assignment operator =

  • Remarkable operators

    • VB: Mod, &, \, And, AndAlso, Or, OrElse

    • C#: ==, !, %, ?:

 

8.4.  Control Structures for Selection
Contents   Up Previous Next   Slide Annotated slide Aggregated slides    Subject index Program index Exercise index 

In this and the following section we will compare the control structures in Visual Basic and C#. We start with the control structures for selection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Module IfDemo

    Sub Main()
      Dim i as Integer, res as Integer
      i = Cint(InputBox("Type a number"))

      If i < 0 Then
        res = -1
        Console.WriteLine("i is negative")
      Elseif i = 0
        res = 0
        Console.WriteLine("i is zero")
      Else 
        res = 1
        Console.WriteLine("i is positive")
      End If
      Console.WriteLine(res)

    End Sub

End Module
Program 8.11    A Visual Basic Program with an If Then Else control structure.

Below we see an if-then-else chain in C#, and above it the equivalent construct in Visual Basic. They are very similar to each other. Notice, in C#, that there must always be parentheses around the boolean expression after if.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;

class IfDemo{

  public static void Main(){
    int i, res;
    i = Int32.Parse(Console.ReadLine());

    if (i < 0){
      res = -1;
      Console.WriteLine("i is negative");
    } 
    else if (i == 0) {
      res = 0;
      Console.WriteLine("i is zero");
    } 
    else { 
       res = 1;
       Console.WriteLine("i is positive");       
    }
    Console.WriteLine(res);
  }

}
Program 8.12    The similar C# program with an if else control structure.

Next we will study the so-called case statement. It is called switch in C# and in other C-like languages. In Visual Basic is called a Select statement. We show a case statement tha finds the number of days in a given month.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Module IfDemo

    Sub Main()
      Dim month as Integer = 2
      Dim numberOfDays as Integer

      Select Case month
        Case 1, 3, 5, 7, 8, 10, 12 
          numberOfDays = 31
        Case 4, 6, 9, 11
          numberOfDays = 30
        Case 2
          numberOfDays = 28             ' or 29
        Case Else 
          Throw New Exception("Problems")
      End Select

      Console.WriteLine(numberOfDays)  ' prints 28
    End Sub
End Module
Program 8.13    A Visual Basic Program with a Select control structure.

There are a number of differences between Select in Visual Basic and switch in C#. In C# the switch statement is designed to jump to a given case. In Visual Basic the individual cases are matched from top to bottom until one of them succeed. In Visual Basic, a Select statement is therefore similar to an if-then-else chain, of the form illustrated in Program 8.11. In Visual Basic it is possible to have simple comparative expressions like it < 3 in a case. This is not possible in C#.

In C# it is necessary to have break statements (or similar jumping commands) in each non-empty case. This prevents case fall trough, as known from C programming. There is no such thing in Visual Basic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

class CaseDemo{

  public static void Main(){
    int month = 2,
        numberOfDays;

    switch(month){
      case 1: case 3: case 5: case 7: case 8: case 10: case 12:
        numberOfDays = 31; break;
      case 4: case 6: case 9: case 11:
        numberOfDays = 30; break;        
      case 2: 
        numberOfDays = 28; break;     // or 29
      default: 
        throw new Exception("Problems");
    }

    Console.WriteLine(numberOfDays);  // prints 28
  }

}
Program 8.14    The similar C# program with a switch control structure.

Let us summarize our experiences with if and switch/select in Visual Basic and C#:

  • If-then-else

    • Similar in the two languages

  • Case

    • C#: Efficient selection of a single case - via underlying jumping

    • VB: Sequential test of cases - the first matching case is executed

    • VB: Select Case approaches the expressive power of an if-then-elseif-else chain

    • Case "fall through" is disallowed in both languages

 

8.5.  Control Structures for Iteration
Contents   Up Previous Next   Slide Annotated slide Aggregated slides    Subject index Program index Exercise index 

We start our coverage of iterative control structures with an example of while. The example below illustrates how to find the greatest common divisor of two integers small and large. (If large happens to be smaller than small we should swap their values). Interesting enough, this particular algorithm - Euclid's algorithm - is usually conceived as the first non-trivial algorithm discovered by mankind.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Module WhileDemo

    Sub Main()
      Dim large As Integer = 106, small As Integer = 30
      Dim remainder As Integer

      While small > 0
        remainder = large Mod small
        large = small
        small = remainder
      End While

      Console.WriteLine("GCD is {0}", large)   ' Prints 2
    End Sub
End Module
Program 8.15    A Visual Basic Program with a while loop.

From the Visual Basic example above and the C# example below we see that the iteration with while is very close to each other in the two languages. In C# we notice that the boolean expression - like in if-else constructs - must be in parentheses.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
class WhileDemo{

  public static void Main(){
    int large = 106, small = 30, remainder;

    while (small > 0){
      remainder = large % small;
      large = small;
      small = remainder;
    }

    Console.WriteLine("GCD is {0}", large);   // Prints 2
  }
}
Program 8.16    The similar C# program with a while loop.

We now turn our interest to iteration with for statements. As a rule of thumb, for statements should be used if we know the number of iterations before the iteration starts.

1
2
3
4
5
6
7
8
9
10
11
12
Module ForDemo

    Sub Main()
      Dim sum As Integer = 0

      For i as Integer = 1 To 10
        sum = sum + i
      Next i

      Console.WriteLine("The sum is {0}", sum)   ' Prints 55
    End Sub
End Module
Program 8.17    A Visual Basic Program with a for loop.

The for control structure in C# is more general - and more powerful - than the For statement in Visual Basic. In C#, a program body is iterated under the control of the three semicolon-separated parts in the parentheses after for:

The init-part consist of initialization of one or more variables. The test-part is a boolean expression; If it becomes false the for-loop stops. The update-part increments or decrements the variables. After execution of the init-part the body is executed if the test-part holds. After execution of body, the update-part is executed, and a new iteration will take place if the test-part holds.

The Visual Basic For statement is similar, but it only controls iteration with use of a single single variable

1
2
3
4
5
6
7
8
9
10
11
12
using System;
class ForDemo{

  public static void Main(){
    int sum = 0;

    for(int i = 1; i <= 10; i++)
      sum = sum + i;

    Console.WriteLine("The sum is {0}", sum);  // Prints 55
  }
}
Program 8.18    The similar C# program with a for loop.

As the last example that involves iteration, we will study a Visual Basic example programmed with a Do-Loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Option Strict On
Option Explicit On
Module DoDemo

    Sub Main()
      Const PI As Double = 3.14159
      Dim radius As Double, area As Double

      Do 
        radius = Cdbl(InputBox("Type radius"))
        If radius < 0 Then
          Exit Do
        End If
        area = PI * radius * radius 
        Console.WriteLine(area)
      Loop

    End Sub
End Module
Program 8.19    A Visual Basic Program with a Do Loop.

The Do-Loop in line 9-16 runs a long as the variable radius is non-negative. In the loop we calculate and output the area of a circle with the given radius. Notice the conditional Exit statement in line 11-13. It is worth noticing that the Visual Basic Do-Loop also allows us to express a Do While.. . Loop (which is similar to a While.. . End While loop as shown in Program 8.15), a Do Until.. . Loop, a Do.. . Loop While, and a Do.. . Loop Until. The two latter alternatives guaranty at least one iteration of the loop body.

In the similar C# program we (mis)use a for loop to program an infinite loop (without control variables). The for loop can be broken by the break statement in line 10. The reason we are tempted to call the C# example a misuse of a for loop is that we do not know - on beforehand - how many times to repeat the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
class ForDemo{

  public static void Main(){
    const double PI = 3.14159;
    double radius, area;

    for(;;){
      radius = double.Parse(Console.ReadLine());
      if (radius < 0) break;
      area = PI * radius * radius;
      Console.WriteLine(area);
    }
  }
}
Program 8.20    The similar C# program with a similar for and a break.

The following items summarize our comparison of Visual Basic and C# iterative control structures:

  • While

    • Very similar in C# and VB

    • C#: Does also support a do ... while

  • Do Loop

    • VB: Elegant, powerful, and symmetric.

    • No direct counterpart in C#

  • For

    • C#: The for loop is very powerful.

    • VB: Similar to classical for loop from Algol and Pascal

The symmetry of the Visual Basic Do Loop is due to the four possible combinations of either while or until in the front or in the end of the construct.

 

8.6.  Arrays
Contents   Up Previous Next   Slide Annotated slide Aggregated slides    Subject index Program index Exercise index 

We will now take a look at arrays. As we soon will realize there are relative large notational differences between Visual Basic and C#, but the underlying array concept is the same in both languages.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Option Strict On
Option Explicit On
Module ArrayDemo

    Sub Main()
      Dim table(9) as Integer  ' indexing from 0 to 9. 

      For i as Integer = 0 To 9
        table(i) = i * i
      Next

      For i as Integer = 0 To 9
        Console.WriteLine(table(i))
      Next

    End Sub
End Module
Program 8.21    A Visual Basic Program with an array of 10 elements.

The array named table is defined in line 6 of both programs. In both languages this creates an array of of ten elements, indexed from 0 to 9. In C# we supply the length of the array [10] whereas in Visual Basic we supply the index of the last element (9). In C# it is always necessary to instantiate the array with an expression like new type [length]. This can also be done in Visual Basic, but in the simple cases - like in line 6 of Program 8.21 - we can avoid this complexity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;

class ArrayDemo{

  public static void Main(){
    int[] table = new int[10];  // indexing from 0 to 9

    for(int i = 0; i <= 9; i++)
      table[i] = i * i;

    for(int i = 0; i <= 9; i++)
      Console.WriteLine(table[i]);
  }
}
Program 8.22    The similar C# program with an array of 10 elements.

  • Notation

    • VB: a(i)

    • C#: a[i]

  • Range

    • Both from zero to an upper limit

    • VB: The highest index is given in an array variable declaration

    • C#: The length of the array is given in an array variable declaration

 

8.7.  Procedures and Functions
Contents   Up Previous Next   Slide Annotated slide Aggregated slides    Subject index Program index Exercise index 

The last area of Visual Basic versus C# comparison will be procedures, functions, and parameter passing. A call of a procedure will affect the state of the program. A call function will return a value to its calling context. Some (impure) functions are both able to return a value, and to affect the state of the program.

In C# parlance, the word "function" covers both the function and procedure concepts. In Visual Basic parlance, a procedure is called a "subprogram" and a function is called a "function". In both languages, functions are allowed to be impure (in the sense that they allow side effects). Both languages support call-by-value and call-by-reference parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Option Strict On
Option Explicit On
Module ArrayDemo

    Sub Sum(ByVal table() As Integer, ByRef result as Integer) 
      result = 0
      For i as Integer = 0 To 9
        result += table(i)
      Next
    End Sub

    Sub Main()
      Dim someNumbers(9) as Integer  
      Dim theSum as Integer = 0

      For i as Integer = 0 To 9
        someNumbers(i) = i * i
      Next
      Sum(someNumbers, theSum)
      Console.WriteLine(theSum)
    End Sub

End Module
Program 8.23    A Visual Basic Program with a procedure - Subprogram.

The procedure Sum adds the elements of the first parameter - an array of integers - together, and it returns the sum in the second parameter called result.

In C# we should notice that Sum is defined a as void function. In the world of C programming it means that the function does not return a value. Thus, it is in reality a procedure. In Visual Basic this is signaled more clearly by using the keywords Sub.. . End Sub.

The first parameter of Sum is a call-by-value parameter. It means that it is copied when Sum is called. (Notice, however, that an array is a reference type in both languages, and therefore it is the reference to the array which is copied. The array itself is not copied. This may be of great confusion to novice programmers! This is true in both Visual Basic and C#). Call-by-value is the default parameter mechanism in both languages. In Visual Basic, the use of call-by-value parameters can be emphasized by using the keyword ByVal).

The second parameter is a call-by-reference parameter. In both languages, a call-by-reference parameter establishes an alias of the actual parameter, which must be a variable. In C# we must use the ref keyword both in front of the formal parameter (in line 4) and in front of the actual parameter (in line 17). In Visual Basic we use the keyword ByRef, but only in the context of the formal parameter (in line 5).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
class ProcedureDemo{

  public static void Sum(int[] table, ref int result){
    result = 0;
    for(int i = 0; i <= 9; i++)
      result += table[i];
  }

  public static void Main(){
    int[] someNumbers = new int[10];
    int theSum = 0;

    for(int i = 0; i <= 9;i++)
      someNumbers[i] = i * i;

    Sum(someNumbers, ref theSum);
    Console.WriteLine(theSum);
  }
}
Program 8.24    The similar C# program with void method.

In the next example we change Sum to a function which returns its result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Option Strict On
Option Explicit On
Module ArrayDemo

    Function Sum(ByVal table() As Integer) as Integer
      Dim result as Integer = 0 
      For i as Integer = 0 To 9
        result += table(i)
      Next
      return result
    End Function

    Sub Main()
      Dim someNumbers(9) as Integer  
      Dim theSum as Integer = 0
      For i as Integer = 0 To 9
        someNumbers(i) = i * i
      Next
      theSum = Sum(someNumbers)
      Console.WriteLine(theSum)
    End Sub

End Module
Program 8.25    A Visual Basic Program with a function.

In the C# program we notice the type int in front of Sum (line 4). This tells us that Sum is an int returning function. In Visual Basic we use the Function...End Function syntax. In both languages we can use the return statement to interrupt the execution of the function, and to return a value to the calling context.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
class ProcedureDemo{

  public static int Sum(int[] table){
    int result = 0;
    for(int i = 0; i <= 9; i++)
      result += table[i];
    return result;
  }

  public static void Main(){
    int[] someNumbers = new int[10];
    int theSum = 0;

    for(int i = 0; i <= 9;i++)
      someNumbers[i] = i * i;

    theSum= Sum(someNumbers);
    Console.WriteLine(theSum);
  }
}
Program 8.26    The similar C# program with int method.

We can now summarize procedures and functions in Visual Basic and C#:

  • Procedures

    • VB: Subprogram

    • C#: void method (void function)

  • Functions

    • VB: Functions

    • C#: int method or someType method

  • Parameter passing

    • Both languages support call by value and call by reference

Generated: Monday February 7, 2011, 12:12:58
Theme index -- Keyboard shortcut: 'u'  Previous theme in this lecture -- Keyboard shortcut: 'p'  Next slide in this lecture -- Keyboard shortcut: 'n'