A C# program consists of the following parts:
-
Namespace declaration
-
A class
-
Class methods
-
Class attributes
-
A Main method
-
Statements and Expressions
-
Comments
Let us look at a simple code that prints the words “Hello World”:
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
}
}
}
let’s break down each line of the C# code:
-
using System;
:
This line tells the compiler to include theSystem
namespace, which provides fundamental functionality for C# programs. -
namespace HelloWorldApplication
:
This line defines a namespace named “HelloWorldApplication” to organize the code.
It acts as a container for classes and helps prevent naming conflicts. -
class HelloWorld
:
This line declares a class named “HelloWorld” within the “HelloWorldApplication” namespace.
Classes are used to define objects and their behavior. -
static void Main(string[] args)
:
This line declares a static method named “Main” with a parameter named “args” of type string array.
The “Main” method is the entry point of the program, and it is automatically executed when the program starts. -
/* my first program in C# */
:
This line is a comment. It is ignored by the compiler and is used to provide notes or explanations to the developers. -
Console.WriteLine("Hello World");
:
This line outputs the string “Hello World” to the console. It displays the message on the screen.