Basic Structure of CSharp Program
Back to: C# .NET Tutorial
C# is a versatile programming language, and understanding its basic structure is essential for writing and executing programs. In this article, we will explore the key components of a C# program and provide code examples for each.
1. Namespace Declaration
Every C# program begins with a namespace declaration. Namespaces provide a way to organize code into logical groups and avoid naming conflicts.
using System;
The using
directive above includes the System
namespace, which contains many commonly used classes and methods.
2. Class Declaration
A C# program typically contains at least one class. The Main
method serves as the entry point for the program.
class Program { static void Main() { // Program logic goes here } }
3. Method Declaration
The Main
method is the starting point for program execution. It is static, which means it belongs to the class rather than an instance of the class.
static void Main() { // Program logic goes here }
4. Statements and Code Blocks
Inside the Main
method, you write statements and code blocks to define the program’s functionality. Statements are executed sequentially, and code blocks enclose a group of statements.
static void Main() { // Single statement Console.WriteLine("Hello, World!"); // Code block { int x = 5; int y = 10; int sum = x + y; Console.WriteLine("Sum: " + sum); } }
5. Comments
Comments are used to add explanations and documentation to the code. They are not executed by the program.
// This is a single-line comment /* This is a multi-line comment */
6. Using External Libraries
To use external libraries or assemblies, you can add additional using
directives at the top of your program.
using System; // System namespace using System.Collections.Generic; // Import additional namespaces
7. Compiling and Running
After writing your C# program, you need to compile it using a C# compiler, such as csc
(C# compiler), and then run the compiled executable.
csc Program.cs // Compile the program Program.exe // Run the compiled program
8. Summary
In summary, a basic C# program consists of a namespace declaration, a class declaration, a Main
method as the entry point, statements and code blocks for logic, comments for documentation, and the use of external libraries when necessary. Understanding this structure is the first step toward becoming proficient in C# programming.