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
IEnumerable<int> 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 <=
foo.GetUpperLimit(); 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 ...