title: Compact timer declaration
body: <p>I have a desktop WPF application that at some point needs to do something on a timely basis. Suppose I use DispatcherTimer class. There's a &quot;long&quot; way:</p>
  <pre><code>public MainWindow()
  {
      // dozens lines of code
  
      timer1.Interval = new TimeSpan(0, 0, 1);
      timer1.Tick += timer1_Tick;
  }
  
  // hundreds lines of code later
  
  DispatcherTimer timer1 = new DispatcherTimer();
  
  void timer1_Tick(object sender, EventArgs e)
  {
      // do stuff
  }
  
  void checkBox1_CheckedChanged(object sender, EventArgs e)
  {
      timer1.IsEnabled = checkBox1.IsChecked.Value;
  }
  </code></pre>
  <p>It works ok, but I don't like that timer-related code is separated in two parts. I could re-create timer each time I start it:</p>
  <pre><code>DispatcherTimer timer1;
  
  void timer1_Tick(object sender, EventArgs e)
  {
      // do stuff
  }
  
  void checkBox1_CheckedChanged(object sender, EventArgs e)
  {
      timer1 = new DispatcherTimer();
      timer1.Interval = new TimeSpan(0, 0, 1);
      timer1.Tick += timer1_Tick;
      timer1.IsEnabled = checkBox1.IsChecked.Value;
  }
  
  </code></pre>
  <p>but that feels wrong.
  Also DispatcherTimer have constructor that take EventHandler as an argument that I may use kinda like that:</p>
  <pre><code>DispatcherTimer timer1 = new DispatcherTimer(
      new TimeSpan(0,0,1),
      DispatcherPriority.SystemIdle,
      new EventHandler(timer1_Tick),
      Dispatcher.CurrentDispatcher);
  
  void timer1_Tick(object sender, EventArgs e)
  {
      // do stuff
  }
  
  void checkBox1_CheckedChanged(object sender, EventArgs e)
  {
      timer1.IsEnabled = checkBox1.IsChecked.Value;
  }
  </code></pre>
  <p>I like it, it's simple and compact, but you can't create EventHandler this way, the compiler says &quot;A field initializer cannot reference the non-static field, method or blah-blah-blah&quot;.</p>
  <p>Is there a way to make this nice code actually work?</p>