C# phân biệt chữ hoa/thường. Lệnh thường kết thúc bằng ;.
Code có thể viết theo kiểu đầy đủ với Main hoặc kiểu rút gọn top-level statements.
| Cú pháp | Dùng để làm gì | Ví dụ |
|---|
using | Import namespace | using System.Text; |
namespace | Nhóm class | namespace MyApp; |
class | Khai báo lớp | class Program { } |
Main | Điểm bắt đầu chương trình | static void Main() |
// | Comment 1 dòng | // ghi chú |
/* */ | Comment nhiều dòng | /* note */ |
Console.WriteLine("Hello");
Console.WriteLine("Xin chào C#");
Console.WriteLine(10 + 5);
Console.Write("Tên của bạn: ");
string? name = Console.ReadLine();
Console.WriteLine($"Xin chào {name}");
Console.WriteLine($"{name} - {age} tuổi");
Console.WriteLine("Không cần class Program khi viết app nhỏ.");
public string Name { get; set; } = "";
| Namespace | Hay dùng cho |
|---|
System | Console, DateTime, Exception |
System.Collections.Generic | List<T>, Dictionary<TKey,TValue> |
System.Linq | LINQ |
System.IO | File, Directory, Path |
System.Text.Json | JSON |
System.Threading.Tasks | Task, async |
static async Task RunAsync()
await File.WriteAllTextAsync("hello.txt", "Hello");
/// Tính tổng hai số nguyên.
int Add(int a, int b) => a + b;
| Thành phần | Quy ước | Ví dụ |
|---|
| Class/Method/Property | PascalCase | ProductService |
| Local variable/parameter | camelCase | productName |
| Interface | Bắt đầu bằng I | IRepository |
| Constant | PascalCase | MaxRetryCount |
- Quên dấu
; ở cuối câu lệnh.
- Viết sai hoa/thường:
console.writeline không đúng.
- Dùng
Console.ReadLine() nhưng quên xử lý giá trị có thể là null.
- Đặt namespace không khớp thư mục làm code khó tìm.
- Quên
using nên compiler báo không tìm thấy type.
syntax, cú pháp, using, namespace, file-scoped namespace, class, Main, entry point, Console.WriteLine, Console.ReadLine, comment, XML comment, top-level statements, coding convention