The following is a short clock program from the book “programming in the key of c#”. I’m not familiar with the Timers library at all so some of this syntax I don’t really get. What I want to understand and I don’t is the line Console.Write(str) in the method in this little program. How does Main know what to print to the console? Is it the empty Console.WriteLine() call that makes the time print out every second? When I’m reading about these concepts it seems easy after the fact to understand what’s going on. Based on what I’ve asked, what are the things about C# that I don’t really understand yet?
using System;
using System.Timers; // Requires System.dll
class Clock
{
static int iStringLength;
static void Main()
{
Console.WriteLine("Press Enter to end program");
Console.WriteLine();
Timer tmr = new Timer();
tmr.Elapsed += new ElapsedEventHandler(TimerHandler);
tmr.Interval = 1000;
tmr.Start();
Console.ReadLine();
tmr.Stop();
}
static void TimerHandler(object obj, ElapsedEventArgs eea)
{
Console.Write(new String('\b', iStringLength));
string str = String.Format("{0} {1} ",
eea.SignalTime.ToLongDateString(),
eea.SignalTime.ToLongTimeString());
iStringLength = str.Length;
Console.Write(str);
}
}
strcontains the value of the string after the String.Format() function is called. That function is documented here: http://msdn.microsoft.com/en-us/library/b1csw23d.aspxIn your code, the {0} is replaced by the formatted representation of eea.SignalTime.ToLongDateString(), and the {1} is replaced by a formatted representation of eea.SignalTime.ToLongTimeString().
So to answer
the answer is “It writes whatever the String.Format() function has determined the value of “str” is in this line:”
The WriteLine() function just prints an empty line and really has nothing to do with the string that shows the date/time as you asked.
For the record, Console.Write and Console.Writeline are documented here and here, respectively.