threads accessing private methods

T

Tony Johansson

Hi!

Here is a simple example on a timer accessing the private method
timer_Elapsed. This works fine.
In this example one might consider that the timer_Elapsed must be public
because the one that is calling is not
within the class.
So I just wonder is it always in such a way that when the framework or the
OS is calling upon a method it can be declared as
private and it will work ?
class Test
{
static void Main()
{
Timer timer = new Timer();
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Interval = 1000;
timer.Enabled = true;
Console.ReadLine();
}

private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Working");
}
}

//Tony
 
G

Göran Andersson

Tony said:
Hi!

Here is a simple example on a timer accessing the private method
timer_Elapsed. This works fine.
In this example one might consider that the timer_Elapsed must be public
because the one that is calling is not
within the class.
So I just wonder is it always in such a way that when the framework or the
OS is calling upon a method it can be declared as
private and it will work ?
class Test
{
static void Main()
{
Timer timer = new Timer();
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Interval = 1000;
timer.Enabled = true;
Console.ReadLine();
}

private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Working");
}
}

//Tony

As the delegate contains a reference to the method, it doesn't matter if
the method is private or not. When the method is called the reference is
used, so whatever is using the delegate doesn't need access to the
method by name.
 
P

Peter Duniho

Tony said:
Hi!

Here is a simple example on a timer accessing the private method
timer_Elapsed. This works fine.
In this example one might consider that the timer_Elapsed must be public
because the one that is calling is not
within the class.

In addition to what Göran wrote, I want to also point out that which
_thread_ is used to execute a method has nothing at all to do with the
accessibility of the method. That is, threads aren't related to
accessibility at all.

Your "Subject:" seems to imply that you believe they are.

Pete
 
H

Harlan Messinger

Peter said:
In addition to what Göran wrote, I want to also point out that which
_thread_ is used to execute a method has nothing at all to do with the
accessibility of the method. That is, threads aren't related to
accessibility at all.

Your "Subject:" seems to imply that you believe they are.

Particularly since in the example given, the calling method and the
called method ARE static methods from the same class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top