-1

I'm working in a Console Application and I want to output the value of an array that exist in the main method inside a timer method. I however have no idea how to send the array values to the timer method as the constructor only takes 4 arguments.

    static void Main(string[] args)
    {
        int[] numbers = new int[7] {1, 2, 3, 4, 5, 6, 7};

        Timer t = new Timer(TimerOutput, 8, 0, 2000);
        Thread.Sleep(10000);
        t.Dispose();

        Console.ReadLine();
    }
    private static void TimerOutput(Object state)
    {
        Console.WriteLine(""); // Here I want to putput the values of numbers[7] from main
        Thread.Sleep(1000);
    }
D Stanley
  • 149,601
  • 11
  • 178
  • 240
Jockiie
  • 19
  • 2
    Move the array(numbers) outside the Main method?... – FakeCaleb Nov 02 '16 at 16:33
  • I am using their values inside the main method for purposes irrelevant to the question. So I need to be able to use its value in both the Main method and the TimerOutput method. – Jockiie Nov 02 '16 at 16:35
  • Your code is missing the class {}, and @NewCallum means "put the numbers array at the class level" -making it a sibling of the main() and timeroutput() methods. – StingyJack Nov 02 '16 at 16:36
  • You should also avoid using a timer when possible. They swallow exceptions and die quietly, leaving your program "running" but doing nothing. – StingyJack Nov 02 '16 at 16:39
  • I also downvoted as it shows absolutely no research or effort. – FakeCaleb Nov 02 '16 at 16:40

1 Answers1

1

Make the array a static property of the Program class. Then the event handler can access it:

private static int[] numbers;

static void Main(string[] args)
{
    numbers = new int[7] {1, 2, 3, 4, 5, 6, 7};

    Timer t = new Timer(TimerOutput, 8, 0, 2000);
    Thread.Sleep(10000);
    t.Dispose();

    Console.ReadLine();
}
private static void TimerOutput(Object state)
{
    // numbers is available in this method.
    Console.WriteLine(""); 
    Thread.Sleep(1000);
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • The past few hours felt like a dead end and you just saved my evening. Thanks a lot, I tried it and it works. Super appreciated! – Jockiie Nov 02 '16 at 16:39