Every C# program shares a basic structure. Understanding these parts will help you read, write, and debug code efficiently.
ποΈ Anatomy of a C# Program
A minimal C# program looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
using System;
namespace MyFirstApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
Key parts:
using System;
β Imports basic features (like Console).namespace
β Groups related code to avoid name conflicts.class Program
β Code lives inside classes.static void Main(string[] args)
β Entry point; code starts here.
β¨ Modern C#: Top-Level Statements
Since C# 9, you can write simple programs without all the boilerplate:
1
Console.WriteLine("Hello, World!");
Great for learning and quick scripts!
π Expanding the Example
Letβs add variables and a method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
namespace MyFirstApp
{
class Program
{
static void Main(string[] args)
{
Greet("C# Beginner");
}
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
}
}
π¦ Organizing Your Code
- Classes: Blueprints for objects.
Place related methods and data together. - Namespaces: Keep code organized, especially in big projects.
π Best Practices
- Name classes and namespaces clearly (e.g.,
CalculatorApp.Math
). - Put each class in its own file in real projects.
π Whatβs Next?
You now understand the basic structure of a C# program. Try modifying the example, adding new methods, or creating your own classes!
Next: Learn the difference between console and web applications.