Click here to Skip to main content
15,891,597 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
static void startWatch_EventArrived(object sender, EventArrivedEventArgs e)
        {
                button1.Text = "";
        }

shows an Error. But when i use private instead of public
C#
private void startWatch_EventArrived(object sender, EventArrivedEventArgs e)
        {
                       button1.Text = "";
        }

problem solved . please explain why this ?
Posted
Comments
Sergey Alexandrovich Kryukov 1-Feb-13 0:50am    
Why do you think you need "static" here? :-)
—SA

This is pretty much by the definition of static. The instance methods (non-static) have an implicit first parameter, this. This is the same very reference which goes on the left of '.' in a call like myInstance.myMethod(); in it myInstance is passed to the method the provide access to the non-static (instance) members of myInstance.

In a static method, such parameters does not exist, that is, this does not exist, so button1 (essentially this.button1, but "this" can be omitted when it does not create an ambiguity), so static method can only access other static members, but not instance members.

In your case, the keyword static simply makes no sense, remove it, and always address throw an instance.

Please see my past past answers:
What makes static methods accessible?[^],
C# windows base this key word related and its uses in the application[^].

—SA
 
Share this answer
 
Static methods can access only static members.
button1 is not a static one.
A static method doesn't have access to members like button1 because it is not a part of that instance.
 
Share this answer
 
hi friends
In your code you use static keyword.
There is some functionality of static keyword as:

1. You can not create the instance of static class .
2. Static methods can not access non static members.
3. you can not access static member of a class using instance of the class.


As in your code you define the method as static so you can not be able to make any instance inside the method.

now in your code :
C#
static void startWatch_EventArrived(object sender, EventArrivedEventArgs e)
        {
                button1.Text = "";
        }

here as the method is static so you can not be able to create any instance of button inside of the method.

now,
C#
private void startWatch_EventArrived(object sender, EventArrivedEventArgs e)
        {
                       button1.Text = "";
        }


in this code you use access specifier i.e,"private" and as the method is not static so you can create any instance inside of the method and you are unable to access that method outside of the class.
I think you are able to understand.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900