Chuyển đến nội dung
Skillpedia
Lập trình chung48k · #5889

csharp

Skill này làm gì

Hướng dẫn này dạy cách viết code C# hiệu quả và rõ ràng hơn, theo các thực hành tốt nhất của ngôn ngữ. Nó đưa ví dụ về cách cải thiện các phần của code để dễ đọc và bảo trì hơn.

Khi nào nên dùng

  • ✓Khi học lập trình C#.
  • ✓Khi xem xét hoặc cải thiện code C# có sẵn.
  • ✓Khi muốn viết code C# hiện đại và an toàn hơn.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/csharp/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/csharp/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để viết code C# gọn gàng hơn khi xử lý danh sách?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Hướng dẫn so sánh cách làm cũ và cách làm mới trong C#. Nó trình bày các ví dụ code cạnh nhau, nêu bật khác biệt và giải thích vì sao cách này tốt hơn cách kia.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

C#: Idiomatic Efficiency Reference

When to Use

  • Use this skill when the task matches this description: Language-specific super-code guidelines for csharp.

Table of Contents

  1. LINQ & Collections
  2. Null Handling
  3. Async/Await
  4. Records & Pattern Matching
  5. Error Handling
  6. Resource Management
  7. Anti-patterns specific to C#

1. LINQ & Collections {#linq}

// ❌ Imperative accumulation
var result = new List<string>();
foreach (var item in items) {
    if (item.IsActive) result.Add(item.Name.ToUpper());
}

// ✅
var result = items
    .Where(i => i.IsActive)
    .Select(i => i.Name.ToUpper())
    .ToList();
// ❌ Manual grouping
var grouped = new Dictionary<string, List<Item>>();
foreach (var item in items) {
    if (!grouped.ContainsKey(item.Category))
        grouped[item.Category] = new List<Item>();
    grouped[item.Category].Add(item);
}

// ✅
var grouped = items.GroupBy(i => i.Category)
    .ToDictionary(g => g.Key, g => g.ToList());
// ❌ Checking Any() then First()
if (items.Any(i => i.IsValid)) {
    var first = items.First(i => i.IsValid);
}

// ✅
var first = items.FirstOrDefault(i => i.IsValid);
if (first is not null) { ... }

Prefer method syntax for chains of 2+ operations. Query syntax is fine for complex joins.


2. Null Handling {#nulls}

// ❌ Nested null checks
string city = null;
if (user != null && user.Address != null) {
    city = user.Address.City;
}

// ✅
var city = user?.Address?.City;
// ❌ Ternary for null fallback
var name = user != null ? user.Name : "Unknown";

// ✅
var name = user?.Name ?? "Unknown";
// ❌ Null check before event invocation
if (OnChanged != null) OnChanged(this, args);

// ✅
OnChanged?.Invoke(this, args);
// ❌ Throwing ArgumentNullException manually
if (name == null) throw new ArgumentNullException(nameof(name));

// ✅ (C# 10+)
ArgumentNullException.ThrowIfNull(name);

Enable nullable reference types (<Nullable>enable</Nullable>) project-wide.


3. Async/Await {#async}

// ❌ Blocking on async code
var result = GetDataAsync().Result; // deadlock risk

// ✅
var result = await GetDataAsync();
// ❌ async void (exceptions are unobservable)
async void OnButtonClick() { await DoWork(); }

// ✅ — async Task; only async void for event handlers that truly require it
async Task OnButtonClick() { await DoWork(); }
// ❌ Sequential awaits for independent work
var a = await FetchA();
var b = await FetchB();

// ✅
var (a, b) = (await Task.WhenAll(FetchA(), FetchB())) switch
{
    var r => (r[0], r[1])
};
// or cleaner with ValueTuple:
var taskA = FetchA();
var taskB = FetchB();
var a = await taskA;
var b = await taskB;
// ❌ Wrapping synchronous code in Task.Run inside a library
public Task<int> GetValue() => Task.Run(() => ComputeSync());

// ✅ — let the caller decide; expose sync method
public int GetValue() => ComputeSync();

Add ConfigureAwait(false) in library code. Omit in app/UI code.


4. Records & Pattern Matching {#records}

// ❌ Manual equality, ToString, Deconstruct for data types
class Point {
    public int X { get; init; }
    public int Y { get; init; }
    // + Equals, GetHashCode, ToString...
}

// ✅ (C# 9+)
record Point(int X, int Y);
// ❌ if-else chain for type checking
if (shape is Circle) {
    var c = (Circle)shape;
    return c.Radius * c.Radius * Math.PI;
} else if (shape is Rectangle) { ... }

// ✅
return shape switch {
    Circle { Radius: var r } => r * r * Math.PI,
    Rectangle { Width: var w, Height: var h } => w * h,
    _ => throw new ArgumentException($"Unknown shape: {shape}")
};
// ❌ Range checking with && 
if (score >= 0 && score <= 100) { ... }

// ✅ (C# 9+)
if (score is >= 0 and <= 100) { ... }

5. Error Handling {#errors}

// ❌ Catching Exception to log and swallow
try { Process(); }
catch (Exception ex) { logger.LogError(ex, "error"); }

// ✅ — catch specific, rethrow if you can't handle
try { Process(); }
catch (HttpRequestException ex) {
    throw new ServiceException("upstream failure", ex);
}
// ❌ throw ex (resets stack trace)
catch (Exception ex) { throw ex; }

// ✅
catch (Exception ex) { throw; } // preserves stack trace
// or wrap: throw new AppException("context", ex);

…
Câu hỏi thường gặp

LINQ là gì?

LINQ (Language Integrated Query) là cách truy vấn và xử lý tập hợp dữ liệu trực tiếp trong ngôn ngữ C#, giúp code gọn hơn.

“Async/Await” nghĩa là gì?

Async/Await là các từ khóa giúp viết code thực hiện tác vụ chạy nền mà không làm đứng chương trình chính, nhờ đó ứng dụng phản hồi nhanh hơn.

“Records” trong C# là gì?

Records là một loại class đặc biệt trong C# dùng để tạo kiểu dữ liệu bất biến, với các tính năng như tự động so sánh bằng và hiển thị chuỗi.

Chi tiết

Mô tả gốc của tác giả

Language-specific super-code guidelines for csharp.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#5889
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự