September 8, 2024

Thread.Sleep() -- a revised example

This does exactly the same as the first example with Thread.Sleep(), we just use some fancy tricks with the Delay property.
using System;
using System.Threading.Tasks;

namespace Example
{
    public class Wally
    {
#if notdef
        private static int delay = 10;

        public static int Delay {
            get { return delay; }
            set { delay = value; }
        }
#endif
        public static int Delay { private get; set; }

        public static void chat ( string msg, int repeat )
        {
            for ( int i=0; i<repeat; i++ ) {
                Console.WriteLine ( msg );
                // Thread.Sleep ( delay );
                Thread.Sleep ( Delay );
            }
        }
    }
}


namespace HogHeaven
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Example.Wally.Delay = 1000;
            Example.Wally.chat ( "Kilroy is here !!", 4 );
            Console.WriteLine ( "All done" );
        }
    }
}
// THE END
First of all notice that in two places I commented out the code from the previous example. I commented out the call to Thread.Sleep() using the usual double slash method. In the other place I use the "if notdef" idiom. This is a common trick in much venerable C code and something you see all the time in legendary project source files. The idea is that "notdef" is never defined (and it better not be). This "just works" regardless of how many other comment blocks, #if blocks, or other rubbish might be enclosed and is standard practice, at least where I come from.
(Another very similar trick is to use #if notyet for obvious purposes.)

The real topic of interest here though is the one line statement:

        public static int Delay { private get; set; }
This replaces all of the Property handling I had written earlier (all 6 lines of it). There is a private field somewhere, but the compiler invents some secret name for it and we don't care. People outside of the all-important "Wally" class can write it, but are not allowed to read it -- but the chat() method in Wally can read it. I had thought I would have to write Wally.Delay to access it from in the chat() method, but I am pleasantly surprised that just "Delay" works fine.

There is some other interesting syntax for writing get and set handlers that look at lot like lambda methods with the "=>" operator, but for now (at least) you will have to look at the books for that. We will eventually talk about lambda methods though.


Feedback? Questions? Drop me a line!

Tom's Computer Info / tom@mmto.org