Multi-line Comments (คอมเมนต์หลายบรรทัด) ใน C# ใช้สำหรับเขียนคำอธิบายที่ยาวกว่าหนึ่งบรรทัด เริ่มต้นด้วย /* และจบด้วย */ คอมไพเลอร์จะละเว้นข้อความทั้งหมดระหว่างเครื่องหมายเหล่านี้
Syntax
/*
นี่คือ Multi-line Comment
สามารถเขียนได้หลายบรรทัด
คอมไพเลอร์จะไม่สนใจข้อความนี้
*/
ตัวอย่างโปรแกรม
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
/* The following is a multi-line
Comment In C#
*/
// printing
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
ผลลัพธ์
Hello World
รูปแบบการใช้งานทั่วไป
1. บล็อกคำอธิบายโมดูล/ฟังก์ชัน
/*
* Module: Payment Processing
* Author: John Doe
* Date: 2024-01-15
* Description: Handles credit card payment validation and processing
*/
public void ProcessPayment(CreditCard card) { ... }
2. ปิดบล็อกโค้ดชั่วคราว (Comment Out Code)
/*
// ระหว่าง Debug - ปิดการทำงานชั่วคราว
var result = CalculateComplexFormula(input);
Console.WriteLine($"Debug: {result}");
// var backup = result.Clone();
*/
3. TODO/NOTE/FIXME Tags
/* TODO: Implement retry logic for network failures
* FIXME: Handle edge case when userId is null
* NOTE: This algorithm is O(n^2) - optimize for large datasets
*/
⚠️ ข้อจำกัดสำคัญ: Nested Comments
C# **ไม่รองรับ Nested Comments** (Comment ซ้อน Comment) - จะ Compile Error
/* Outer comment
/* Inner comment */ // ERROR: Unexpected end of comment
More outer comment
*/
XML Documentation Comments (///)
สำหรับสร้างเอกสาร API อัตโนมัติ (IntelliSense, DocFX, Sandcastle)
///
/// Calculates the factorial of a number.
///
/// Non-negative integer
/// Factorial of n
/// Thrown when n < 0
public static long Factorial(int n) {
if (n < 0) throw new ArgumentException("n must be non-negative");
return n <= 1 ? 1 : n * Factorial(n - 1);
}
เปรียบเทียบ Comment Types ใน C#
| ประเภท | Syntax | ใช้เมื่อไหร่ | IntelliSense |
|---|---|---|---|
| Single-line | // comment |
คำอธิบายสั้น บรรทัดเดียว | ไม่ |
| Multi-line | /* comment */ |
คำอธิบายยาว หลายบรรทัด, Comment Out Code | ไม่ |
| XML Doc | /// comment |
Public API Documentation | ✅ ใช่ |
Best Practices
- ใช้
//สำหรับ Inline Comments และ Short Explanations - ใช้
/* */สำหรับ Block Comments, File Headers, Comment Out Code Blocks - ใช้
///สำหรับ Public APIs (Classes, Methods, Properties, Events) - หลีกเลี่ยง Comment ที่อธิบาย "Code ทำอะไร" (Self-documenting Code ดีกว่า)
- Comment ควรอธิบาย "ทำไม" (Why) ไม่ใช่ "ทำอะไร" (What)
- Update Comments เมื่อแก้ไข Code - Outdated Comments หายากกว่า No Comments