Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่างระหว่าง String และ string ใน C#

คำตอบสั้นๆ

string (ตัวพิมพ์เล็ก) เป็น Alias (นามแฝง) ของ System.String ใน C#

String (ตัวพิมพ์ใหญ่) คือชื่อคลาสจริงใน .NET Framework (System.String)

ทั้งคู่นี้คือสิ่งเดียวกันทุกประการ - คอมไพเลอร์จะแปลง string ให้เป็น System.String อัตโนมัติ

ตัวอย่างการใช้งาน

// ทั้งคู่นี้เทียบเท่ากัน 100%
string str1 = "Hello";
String str2 = "World";
System.String str3 = "!";

// ใช้ String เมื่อเข้าถึง Static Methods
string formatted = String.Format("Welcome {0}!", "User");
string compared = String.Compare(str1, str2);
bool isNullOrEmpty = String.IsNullOrEmpty(str1);

// ใช้ string สำหรับตัวแปรทั่วไป (Microsoft Recommendation)
string name = "John";
string message = "Hello " + name;

Alias ของชนิดข้อมูลพื้นฐานอื่นๆ

Alias (C#) .NET Type (System) คำอธิบาย
object System.Object Base type ของทุกอย่าง
string System.String Unicode String (Immutable)
bool System.Boolean True/False
byte System.Byte Unsigned 8-bit (0-255)
sbyte System.SByte Signed 8-bit (-128 to 127)
short System.Int16 Signed 16-bit
ushort System.UInt16 Unsigned 16-bit
int System.Int32 Signed 32-bit
uint System.UInt32 Unsigned 32-bit
long System.Int64 Signed 64-bit
ulong System.UInt64 Unsigned 64-bit
float System.Single 32-bit Floating Point
double System.Double 64-bit Floating Point
decimal System.Decimal 128-bit High Precision
char System.Char Single Unicode Character

แนวทางปฏิบัติที่แนะนำ (Microsoft Coding Conventions)

  • ใช้ string (lowercase) สำหรับการประกาศตัวแปรและพารามิเตอร์
  • ใช้ String (PascalCase) เมื่อเข้าถึง Static Members เช่น String.Format, String.Compare, String.IsNullOrEmpty
  • เหตุผล: string เป็น Keyword ของ C# ทำให้อ่านโค้ดง่ายขึ้นและสอดคล้องกับ Primitive Types อื่นๆ (int, bool, double)

ตัวอย่างโค้ดที่ปฏิบัติตาม Convention

public class UserService {
    // ใช้ string สำหรับตัวแปร
    private string _connectionString;
    
    public UserService(string connectionString) {
        _connectionString = connectionString;
    }
    
    // ใช้ String สำหรับ Static Methods
    public string GetFullName(string firstName, string lastName) {
        if (String.IsNullOrEmpty(firstName)) {
            throw new ArgumentException("First name required");
        }
        
        return String.Format("{0} {1}", firstName, lastName);
    }
}