Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a necessary to have at least one class in C#

In Java, we need to have at least a class to hold the main method.

When I create a C# project, the skeleton code looks similar to the Java skeleton codes.

However, should there always be at least one class for the main function in C#?

namespace Hello_World
{
    class Hello   //Is it compulsory to have this class ?
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.ReadKey();

        }
    }
}

Edit: I am assuming at least one class is needed in a most basic C# program as the main method needs to be contain within a class. Since main() is needed to run a program, at least one class is needed. Am I right to say that?

like image 284
user3437460 Avatar asked Jan 28 '26 23:01

user3437460


1 Answers

No, not necessarily. You can have a struct also. Following is a perfectly valid c# program.

namespace NoClass
{
    struct Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world");
        }
    }
}

Fact that Method should be inside a type in c# you need a enclosing type for your main method. It can be struct or class. It is your choice. but you can't have global funcions in c#.

like image 189
Sriram Sakthivel Avatar answered Jan 31 '26 13:01

Sriram Sakthivel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!