Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# : console application - static methods

Tags:

c#

static

why in C#, console application, in "program" class , which is default, all methods have to be static along with

static void Main(string[] args) 
like image 604
dotnet-practitioner Avatar asked Nov 06 '09 05:11

dotnet-practitioner


People also ask

What is C in coding language?

C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on. C programming is an excellent language to learn to program for beginners. Our C tutorials will guide you to learn C programming one step at a time.

What is C full form?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C language w3schools?

C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

Member functions don't have to be static; but if they are not static, that requires you to instantiate a Program object in order to call a member method.

With static methods:

public class Program {     public static void Main()     {         System.Console.WriteLine(Program.Foo());     }      public static string Foo()     {         return "Foo";     } } 

Without static methods (in other words, requiring you to instantiate Program):

public class Program {     public static void Main()     {         System.Console.WriteLine(new Program().Foo());     }      public string Foo() // notice this is NOT static anymore     {         return "Foo";     } } 

Main must be static because otherwise you'd have to tell the compiler how to instantiate the Program class, which may or may not be a trivial task.

like image 75
Mark Rushakoff Avatar answered Sep 23 '22 03:09

Mark Rushakoff


You can write non static methods too, just you should use like this

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

The only requirement for C# application is that the executable assembly should have one static main method in any class in the assembly!

like image 27
Arsen Mkrtchyan Avatar answered Sep 24 '22 03:09

Arsen Mkrtchyan