BusinessRx Community

Dedicated to the advancement of software, technology and the people who devote their lives to it.

Welcome to BusinessRx Community Sign in | Join | Help
in Search

BusinessRx Reading List

These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.

Looping 101

Here is a pop quiz for language aficionados.

Examine the following class:

public class Foo
{
   
public int GetUpperLimit()
    {
        Console.WriteLine(
"GetUpperLimit invoked");
       
return 5;
    }

   
public IEnumerableint> GetCollection()
    {
        Console.WriteLine(
"GetCollection invoked");
       
return new int[] { 1, 2, 3, 4, 5 };
    }
}

Now examine the following console mode program:

class Program
{
   
static void Main(string[] args)
    {
       
Foo foo = new Foo();

       
for (int i = 1; i         {
           
Console.WriteLine(i);
        }

        foreach (int i in foo.GetCollection())
        {
           
Console.WriteLine(i);
        }
    }
}

 Without using a compiler, do you know:  

  • How many times "GetUpperLimit invoked" will appear in the output?
  • How many times "GetCollection invoked" will appear in the output?

Now, examine the same console program in VB:

Sub Main()
   
Dim foo As New Foo()

   
For i As Integer = 1 To foo.GetUpperLimit()
        Console.WriteLine(i)
   
Next

    For Each i As Integer In foo.GetCollection()
        Console.WriteLine(i)
   
Next
End
Sub

 Bonus third question:  

  • Will the output of the VB program be the same as the C# program?

I was suprised by the answer to the last question ...

Published Saturday, April 28, 2007 9:12 PM by OdeToCode Blogs

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server, by Telligent Systems
'