C#: Basic Syntax

1. Program Structure

A classic C# program consists of using directives, a namespace, a class, and a Main method.

▶ Example

CSHARP
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}
▶ Try it Yourself
TEXT 📖 Display only
Hello, World!

2. Statements and Semicolons

Every statement in C# must end with a semicolon ;. The semicolon is a statement terminator that tells the compiler where one instruction ends. A missing semicolon will cause a compilation error.

▶ Example

CSHARP
using System;

namespace StatementDemo
{
    class Program
    {
        static void Main()
        {
            int x = 10;
            int y = 20;
            int sum = x + y;
            Console.WriteLine(sum);
        }
    }
}
▶ Try it Yourself
TEXT 📖 Display only
30

3. Code Blocks and Braces

A code block is wrapped in braces { }, grouping multiple statements into a single logical unit. Namespaces, classes, methods, conditionals, and loops all require code blocks. Braces can be nested.

CSHARP
namespace Outer
{
    namespace Inner
    {
        class MyClass
        {
            void MyMethod()
            {
                if (true)
                {
                    Console.WriteLine("nested block");
                }
            }
        }
    }
}

4. Indentation and Code Style

Good indentation makes code easier to read. The C# community recommends 4 spaces for indentation. There are two common brace styles:

CSHARP
class StyleA
{
    void Method()
    {
        Console.WriteLine("Allman style");
    }
}

class StyleB {
    void Method() {
        Console.WriteLine("K&R style");
    }
}

Tip: Visual Studio uses Allman style by default. What matters most is consistency within a project.


5. Console Output

Console.Write and Console.WriteLine are used to output text to the console:

▶ Example

CSHARP
using System;

namespace ConsoleDemo
{
    class Program
    {
        static void Main()
        {
            Console.Write("Hello");
            Console.Write(" ");
            Console.WriteLine("World");
            Console.WriteLine("Second line");
        }
    }
}
▶ Try it Yourself
TEXT 📖 Display only
Hello World
Second line

6. Escape Characters

Certain characters inside strings must be escaped with a backslash \ to be represented correctly:

Escape Sequence Meaning
\n Newline
\t Tab
\\ Backslash
\" Double quote
\' Single quote

▶ Example

CSHARP
using System;

namespace EscapeDemo
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Line1\nLine2");
            Console.WriteLine("Name\tAge");
            Console.WriteLine("Path: C:\\Users\\Doc");
            Console.WriteLine("He said \"Hello\"");
        }
    }
}
▶ Try it Yourself
TEXT 📖 Display only
Line1
Line2
Name	Age
Path: C:\Users\Doc
He said "Hello"

Warning: If a string contains many backslashes (such as file paths), use a verbatim string @"...", where \ no longer needs escaping.


7. Comments

Comments are notes for developers and are ignored by the compiler. C# supports three types of comments:

CSHARP
using System;

namespace CommentDemo
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("hello");

            Console.WriteLine("world");

            /*
            Console.WriteLine("skipped");
            Console.WriteLine("also skipped");
            */

            Console.WriteLine("end");
        }

        /// <summary>
        /// Calculate the sum of two numbers
        /// </summary>
        static int Add(int a, int b)
        {
            return a + b;
        }
    }
}
TEXT 📖 Display only
hello
world
end

Tip: XML documentation comments (///) are commonly used for public APIs. Visual Studio displays these descriptions when the method is called.


8. Top-Level Statements

Starting with C# 9, top-level statements let you skip the boilerplate namespace, class, and Main code, writing logic directly at the file's top level. The compiler automatically generates the entry method.

▶ Example

CSHARP
using System;

Console.WriteLine("Top-level statement!");
int result = 40 + 2;
Console.WriteLine($"The answer is {result}");
▶ Try it Yourself
TEXT 📖 Display only
Top-level statement!
The answer is 42

Tip: Top-level statements can only be used in one file per project. Using them in multiple files causes a compilation error.


9. File-Scoped Namespaces

Starting with C# 10, file-scoped namespaces let you use namespace MyApp; instead of the traditional block-style namespace, reducing one level of nesting:

CSHARP
namespace MyApp;

class Program
{
    static void Main()
    {
        Console.WriteLine("File-scoped namespace");
    }
}

This is equivalent to:

CSHARP
namespace MyApp
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("File-scoped namespace");
        }
    }
}

Tip: File-scoped namespaces make code more concise and are recommended for new projects.

❓ FAQ

Q What happens if I forget a semicolon?
A The compiler will report an error indicating a missing semicolon, and the error location may point to the next line.
Q Can using directives be placed inside a namespace?
A Yes, but they are typically placed at the top of the file for clearer scoping.
Q Can I define classes in a project that uses top-level statements?
A Yes, just place class definitions after the top-level statements.
Q Can I define multiple namespaces in a file-scoped namespace?
A No, each file can only have one file-scoped namespace.

📖 Summary

📝 Exercises

  1. Write a console program that uses Console.Write and Console.WriteLine to output your name and age
  2. Use escape characters to output three lines of text in a single Console.WriteLine statement
  3. Rewrite a classic program structure using top-level statements
  4. Add XML documentation comments to a method, including <summary> and <param> tags
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏