Ben
Ben

Reputation: 2523

Why can't I call 'public void' from the same class?

My understanding of the method structures is limited to a very limited spectrum of structures:

public / private
static
void / variable returns
string, int etc.

So why can't I call a method within the same class?

class ClassName
{
    public void Method1()
    {
        // do stuff...
    }

    public static void Method2()
    {
        // This won't work?
        Method1();

        // do stuff...
    }
}

Upvotes: 1

Views: 2139

Answers (3)

Amaranth
Amaranth

Reputation: 2511

You can't call a non static element from a static context. You would have to create an instance of your class in your static method and call the non static method from that instance. A static method can be called without an instance.

Upvotes: 1

Saverio Terracciano
Saverio Terracciano

Reputation: 3915

You can't call a non-static method from a static method. If you really want to do that from withing a static method, you need to instantiate the class, something like:

    class myClass
    {
        public void Method1(){
          //Stuffs
        }

        public static void Method2(){
         myClass c=new myClass();
        c.Method1();
        }
     }

Upvotes: 3

Gabriel GM
Gabriel GM

Reputation: 6649

You can't call a method that isn't static from a static method..

Static = belongs to the class

Otherwise it belongs the instance of the class.

See MSDN reference for more information about static methods.

Upvotes: 1

Related Questions