Sidney
Sidney

Reputation: 176

How to call a non static method in the main?

class Program
    {
        static void Main(string[] args)
        {
            //I want to call the bird method here
        }

        public void bird(Program program)
        {
            birdSpeech();
        }

        public void birdSpeech()
        {
            Console.WriteLine("Chirp Chirp");
        }
    }
  1. How do I call bird in the main, I also tried to call the method from a object of the class but that didn't work

  2. Does it even make sense to do this (I try to avoid static methods as much as possible).

Upvotes: 2

Views: 2406

Answers (2)

Cowboy
Cowboy

Reputation: 1066

Could do something like this

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var p = new Program();
        p.bird(p);
    }

    public void bird(Program program)
    {
        birdSpeech();
    }

    public void birdSpeech()
    {
        Console.WriteLine("Chirp Chirp");
    }
}

Upvotes: 1

Leo
Leo

Reputation: 1303

If a method can be made static without changing the code, you should make it static. To answer your question though, you can create an instance of Program in your Main function and call the non-static methods through it.

class Program
{
        static void Main(string[] args)
        {
            var p = new Program();
            p.bird();
        }

        public void bird()
        {
            birdSpeech();
        }

        public void birdSpeech()
        {
            Console.WriteLine("Chirp Chirp");
        }
}

Upvotes: 2

Related Questions