0

I write next code:

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += (object sender, EventArgs e) =>
{
    //...
};
timer.Start();

But I wanna write this more simply with the intializer.

So, I tried this:

new DispatcherTimer
{
    Interval = TimeSpan.FromSeconds(1),
    Tick += (object sender, EventArgs e) =>
    {
        //...
    }
}.Start();

But it occurs errors(CS0103, CS0747).

Is it impossible expression?

Jeffrey Kang
  • 77
  • 1
  • 8

1 Answers1

1

The stuff in the curly brackets is the initializer section in which you can initialize public properties or fields only. The line

Tick += etc

Is not initializing Tick, it is adding an event handler to it using += which is not possible.

You can however use this constructor:

new DispatcherTimer(
    TimeSpan.FromSeconds(1),
    DispatcherPriority.Normal,
    (sender, args) =>
    {
    //...
    },
    Application.Current.Dispatcher)
        .Start();

Personally I think the several lines of code option is easier to read.

Tim Rutter
  • 4,549
  • 3
  • 23
  • 47