views:

77

answers:

2

Hi all

Is there any possible way to access the field - str in the Class Program and the variable num - in the main function?

class Program
{
    string str = "This is a string";
    static void Main(string[] args)
    {
        int num = 100;
        Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
        var timer = new System.Timers.Timer(10000);
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        timer.Start();
        for (int i = 0; i < 20; i++)
        {
            Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + "current I is " + i.ToString());
            Thread.Sleep(1000);
        }
        Console.ReadLine();
    }

    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Debug.WriteLine(str);
        Debug.WriteLine(num);
        Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + "  current is timer");
        //throw new NotImplementedException();
    }
}

Best Regards,

+1  A: 

The field just needs to be made static.

static string str = "This is a string";

To access num you need to use a lambda expression.

timer.Elapsed += new ElapsedEventHandler((s, e) =>
{
     Debug.WriteLine(str);
     Debug.WriteLine(num);
     Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + "  current is timer");

});

You can also use an anonymous method.

timer.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
{
     Debug.WriteLine(str);
     Debug.WriteLine(num);
     Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + "  current is timer");

});

There is one more option. The System.Threading.Timer class allows you to pass a state object.

var timer = new System.Threading.Timer((state) =>
{
     Debug.WriteLine(str);
     Debug.WriteLine(state);
     Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + "  current is timer");
}, num, 10000, 10000);
ChaosPandion
Didnt think about doing it with an anonymous method.
GrayWizardx
If you are interested you may want read up on closures. http://en.wikipedia.org/wiki/Closure_%28computer_science%29
ChaosPandion
A: 

str should be accessible directly if you change it to static as its implemented now since it is at class level. Num is internal to main and so cannot be accessed unless you pass a reference to it. You can move it external to main, or if its supported in ElapsedEventArgs pass a reference to it and retrieve it that way.

GrayWizardx
Just checked and it looks like ElapsedEventArgs doesnt have an object to hold state. You will need to provide either a global reference (move the num to the class level) or provide a reference pointer that can reach it using a delegate or similar.
GrayWizardx