NESHOM
NESHOM

Reputation: 929

Call functions in the Main method

Why running this C# code shows error on F1(); in Main?

namespace Project1
{
    public partial class Program1
    {       
        private void F1()
        {
            Console.WriteLine("F2");
        }

        private void F2()
        {
            Console.WriteLine("F1");
        }

        static void Main(string[] args)
        {
            F1();
        }
    }
}

This is a console application. It works if I define an object of class Program1. But when I try this on a Windows Form Application, I can put F1(); in a button_click event and it runs without error without defining an object of Class Form1?

Upvotes: 1

Views: 1403

Answers (2)

shree.pat18
shree.pat18

Reputation: 21757

You have not defined the methods as static. Therefore you need to create an instance of your class first and then call them using that instance.

If you want to call the methods directly, you could make them static. In this case since you seem to be just displaying static text it would be fine to do so. However, often, methods will actually need to act on instances and so must be called as such. You may want to look at this question, which discusses when it makes sense to make your methods static.

Upvotes: 3

mdebeus
mdebeus

Reputation: 1928

Below are two alternatives:

namespace Project1
{
public partial class Program1
{       
    private void F1()
    {
        Console.WriteLine("F1");
    }

    private void F2()
    {
        Console.WriteLine("F2");
    }

    static void Main(string[] args)
    {
        var program1 = new Program1();
        program1.F1();
    }
}
}

OR...

namespace Project1
{
public partial class Program1
{       
    static private void F1()
    {
        Console.WriteLine("F1");
    }

    static private void F2()
    {
        Console.WriteLine("F2");
    }

    static void Main(string[] args)
    {
        F1();
    }
}
}

BTW, I changed your WriteLine text to reflect the function being called.

Upvotes: 2

Related Questions