csharp
하는 일
이 가이드는 C#의 모범 사례에 따라 코드를 더 효율적이고 명확하게 작성하는 방법을 가르칩니다. 코드 일부를 개선해 읽기와 유지보수를 쉽게 하는 예시를 보여 줍니다.
사용하는 경우
- ✓C#으로 프로그래밍을 배울 때.
- ✓기존 C# 코드를 검토하거나 개선할 때.
- ✓더 현대적이고 안전한 C# 코드를 작성하고 싶은 경우.
스킬 링크
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/csharp/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“리스트를 다루는 C# 코드를 더 깔끔하게 작성하려면 어떻게 해야 하나요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
이 가이드는 C#의 예전 방식과 새로운 방식을 비교합니다. 코드 예시를 나란히 보여 주며 차이를 강조하고, 왜 한쪽이 더 나은지 설명합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
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
- LINQ & Collections
- Null Handling
- Async/Await
- Records & Pattern Matching
- Error Handling
- Resource Management
- 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);
…
자주 묻는 질문
LINQ란 무엇인가요?
LINQ(Language Integrated Query)는 C# 언어 안에서 데이터 모음을 직접 조회하고 다룰 수 있게 해 주는 방법입니다. 코드를 더 간결하게 만듭니다.
'Async/Await'는 무엇을 뜻하나요?
Async/Await는 주 프로그램을 멈추지 않고 백그라운드 작업을 수행하는 코드를 쓰도록 돕는 키워드입니다. 응답성을 높입니다.
C#의 'Records'란 무엇인가요?
Records는 변경할 수 없는 데이터 중심 타입을 쉽게 만드는 특별한 종류의 클래스입니다. 자동 동등성 비교와 문자열 표현 같은 기능이 있습니다.
상세 정보
인기도
- GitHub 스타
- 48k
- 순위
- #5889
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
00-andruia-consultant
48k에이전트가 AI 프로젝트를 시작하거나 개선할 수 있도록 코드를 분석하고 스페인어로 실행 계획을 세워 줍니다.
007
48k에이전트가 보안 감사와 위협 모델링을 수행해 공격과 취약점으로부터 프로젝트를 보호하도록 돕습니다.
10-andruia-skill-smith
48k에이전트가 AI 도구의 작동 방식을 정의하고 문서를 쓰며 구조를 검증하도록 돕습니다.
20-andruia-niche-intelligence
48k에이전트가 신뢰할 수 있는 자료를 바탕으로 특정 산업의 맥락, 규칙, 사용 패턴, 위험을 정리한 요약을 만들도록 돕습니다.