Bỏ qua để đến nội dung

Cú pháp cơ bản

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ápDùng để làm gìVí dụ
usingImport namespaceusing System.Text;
namespaceNhóm classnamespace MyApp;
classKhai báo lớpclass Program { }
MainĐiểm bắt đầu chương trìnhstatic void Main()
//Comment 1 dòng// ghi chú
/* */Comment nhiều dòng/* note */
using System;
namespace MyApp;
class Program
{
static void Main()
{
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}");
string name = "Dung";
int age = 20;
Console.WriteLine($"{name} - {age} tuổi");
Console.WriteLine("Không cần class Program khi viết app nhỏ.");
namespace MyApp.Models;
public class User
{
public string Name { get; set; } = "";
}
NamespaceHay dùng cho
SystemConsole, DateTime, Exception
System.Collections.GenericList<T>, Dictionary<TKey,TValue>
System.LinqLINQ
System.IOFile, Directory, Path
System.Text.JsonJSON
System.Threading.TasksTask, async
await RunAsync();
static async Task RunAsync()
{
await File.WriteAllTextAsync("hello.txt", "Hello");
}
/// <summary>
/// Tính tổng hai số nguyên.
/// </summary>
int Add(int a, int b) => a + b;
Thành phầnQuy ướcVí dụ
Class/Method/PropertyPascalCaseProductService
Local variable/parametercamelCaseproductName
InterfaceBắt đầu bằng IIRepository
ConstantPascalCaseMaxRetryCount
  • 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