Monday, January 23, 2006

Want to get lost with C#?

Following is very simple C# source. Read it and think if all TimeSpans will have almost same value or not. After you make up your mind about the answer, simply run and see results. That may surprise you. Then try different things like – check for release version, check with code optimization ON in project properties, make fifth loop go for 15000 times etc.

Keep yourself busy and bemused!

using System;
namespace Test

{
class Program
{
public static Program prg = new Program();
static public TimeSpan ts1, ts2, ts3, ts4, ts5;

static void Main( string[] args )
{
DateTime start1 = DateTime.Now;
Program.MyMethod(10000);
Program.ts1 = DateTime.Now - start1;

DateTime start2 = DateTime.Now;
Program.MyMethod(10000);
Program.ts2 = DateTime.Now - start2;

DateTime start3 = DateTime.Now;
Program.MyMethod(10000);
Program.ts3 = DateTime.Now - start3;

DateTime start4 = DateTime.Now;
Program.MyMethod(10000);
Program.ts4 = DateTime.Now - start4;

DateTime start5 = DateTime.Now;
Program.MyMethod(10000);
Program.ts5 = DateTime.Now - start5;

Console.WriteLine(Program.ts1);
Console.WriteLine(Program.ts2);
Console.WriteLine(Program.ts3);
Console.WriteLine(Program.ts4);
Console.WriteLine(Program.ts5);
Console.ReadLine();
}
public static int MyMethod(int N)
{
for(int counter = 0; counter < N; counter++)
Console.WriteLine(counter);
return 0;
}
}
}