tags:

views:

185

answers:

2

Can I call(access) non static method from static method ?? Like I have static method If yes, how??

public static void method()      //like this is a static method
{
    methodsec();        //from here I want to access non static method defined below
}

public void methodsec()      // non static method
{

}
+4  A: 

Yes, but you need a reference to do it through:

public static void StaticMethod()    
{
     someInstance.InstanceMethod();
}

public void InstanceMethod()
{
}

You need to think about which instance you want to call the method on. Instance methods typically use the state of the instance, so the method is likely to do different things depending on which instance it's called on.

Jon Skeet
Instance like??
Harikrishna
instance is the object you want to call the function on. For example: Fruit apple = new Fruit(); apple.BlowUp(); apple is the instance
PoweRoy
@Harikrishna: Well which instance do you *want* to call it on? Suppose this is a control of some description, you've got two controls on the screen, and the method will change the text in the control - obviously you need to say *which* control you want to change the text of.
Jon Skeet
And if instead of this non static method there is buttonclick event then what should I do??
Harikrishna
+1  A: 

No you can't call it exactly like that. You either need an instance of the class to call the non-static method, or it also needs to be static.

An alternative approach would be to use a singleton pattern - so you only have one instance of the class available throughout your code, and don't need to use static methods. That way, all methods in the class can call each other. It's hard to tell whether this would actually suit your needs, without further info but could be the way to go

AdaTheDev