C Sharp Tricks

From Hobowiki
Revision as of 09:28, 20 April 2021 by Brendan (talk | contribs)
Jump to navigation Jump to search

Here is a list of things that I've learned from C# that seem to be useful to me in some manner or another at some point or another. Also, I would have called it Stupid C# Tricks, but I can't due to technical restrictions.

Anonymous Timer Method

When doing testing, sometimes it's useful to try and step on the toes of your methods while in progress in order to emulate reality. In order to do this, sometimes what is required is a timer elapsing in the middle of execution of another method. Without going into all the hairy business of building a separate method or class to house all the timer pieces, you can simply build a short little anonymous timer that gives you the options you need. Here's a quick little example using Delegates.

System.Timers.Timer t = new System.Timers.Timer(2000);
System.IO.FileStream file;
t.Elapsed += new System.Timers.ElapsedEventHandler(delegate(object s, System.Timers.ElapsedEventArgs e)
{
    file = new System.IO.FileStream("myfile.txt", System.IO.FileMode.Open);
    ((System.Timers.Timer)s).Stop();
});
System.Timers.Timer t2 = new System.Timers.Timer(4000);
t.Elapsed += new System.Timers.ElapsedEventHandler(delegate(object s, System.Timers.ElapsedEventArgs e)
{
    if (file != null) file.Close();
    ((System.Timers.Timer)s).Stop();
});
t.Start();
t2.Start();

This will wait 2 seconds, open a file for reading, then 2 seconds later it will close that file.