404 Not Found

404 Not Found


nginx

Basic Syntax

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
Hello, World!

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
30

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");
                }
            }
        }
    }
}

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.

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
Hello World
Second line

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
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.

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
hello
world
end

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

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
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.

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

  • A C# program consists of using directives, namespace, class, and Main method
  • Every statement must end with a semicolon
  • Code blocks are wrapped in braces and can be nested
  • Console.Write does not add a newline; Console.WriteLine does
  • Escape characters use a backslash prefix; verbatim strings @"..." avoid escaping
  • Three comment types: single-line //, multi-line /* */, XML doc ///
  • Top-level statements (C# 9+) simplify entry-point code
  • File-scoped namespaces (C# 10+) reduce nesting levels

📝 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%

🙏 帮我们做得更好

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

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