Structure of a C# Program

Understanding the fundamental building blocks

Posted by Rodrigo Castro on October 6, 2024

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.