คีย์เวิร์ด this คืออะไร?
this ใน C# เป็นคีย์เวิร์ดที่อ้างอิงถึง อินสแตนซ์ปัจจุบัน (current instance) ของคลาส ใช้เพื่อแยกแยะระหว่างพารามิเตอร์ของเมธอดกับฟิลด์ของคลาสที่มีชื่อเหมือนกัน และใช้เรียก Constructor อื่นในคลาสเดียวกัน
การใช้งานหลัก 3 แบบ
1. แยกแยะ Field และ Parameter (Qualifying Fields)
เมื่อพารามิเตอร์เมธอด/คอนสตรัคเตอร์มีชื่อเหมือนกับ Field
public class Student
{
public int Id;
public string Name;
public int Age;
public string Subject;
public Student(int id, string name, int age, string subject)
{
// this.Id = field ของคลาส, id = parameter
this.Id = id;
this.Name = name;
this.Age = age;
this.Subject = subject;
}
}
2. เรียก Constructor อื่นในคลาสเดียวกัน (Constructor Chaining)
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Subject { get; set; }
// Constructor หลัก
public Student(int id, string name, int age, string subject)
{
Id = id;
Name = name;
Age = age;
Subject = subject;
}
// Constructor ที่เรียก constructor หลัก (chaining)
public Student(int id, string name) : this(id, name, 0, "Unknown") { }
public Student() : this(0, "Unknown", 0, "Unknown") { }
}
3. ส่งอินสแตนซ์ปัจจุบันไปให้เมธอดอื่น (Passing Current Instance)
public class Logger
{
public void Log(string message) => Console.WriteLine($"[LOG] {message}");
}
public class Service
{
private Logger _logger = new Logger();
public void DoWork()
{
// ส่ง this (Service instance) ไปให้ Logger
_logger.Log($"Service {this.GetHashCode()} เริ่มทำงาน");
ProcessData(this); // ส่งตัวเองไป
}
private void ProcessData(Service service)
{
// ทำงานกับ service instance
}
}
ตัวอย่างโค้ดสมบูรณ์ (Student Record)
using System;
class Student
{
public int Id;
public string Name;
public int Age;
public string Subject;
public Student(int id, string name, int age, string subject)
{
this.Id = id;
this.Name = name;
this.Subject = subject;
this.Age = age;
}
public void ShowInfo()
{
Console.WriteLine($"{Id} {Name} {Age} {Subject}");
}
}
class StudentDetails
{
public static void Main(string[] args)
{
Student std1 = new Student(001, "Jack", 23, "Maths");
Student std2 = new Student(002, "Harry", 27, "Science");
Student std3 = new Student(003, "Steve", 23, "Programming");
Student std4 = new Student(004, "David", 27, "English");
std1.ShowInfo();
std2.ShowInfo();
std3.ShowInfo();
std4.ShowInfo();
}
}
ผลลัพธ์
1 Jack 23 Maths
2 Harry 27 Science
3 Steve 23 Programming
4 David 27 English
การใช้งาน this กับ Extension Methods
ใน Extension Methods ใช้ this ก่อนพารามิเตอร์แรก เพื่อระบุประเภทที่ขยาย
public static class StringExtensions
{
// this string str = ขยายจาก string
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
}
// ใช้งาน
string s = "Hello";
bool empty = s.IsNullOrEmpty(); // เรียกเหมือน instance method
this ใน Structs
ใน struct (Value Type) this หมายถึง copy ของ struct ไม่ใช่ reference
public struct Point
{
public int X, Y;
public void Move(int dx, int dy)
{
// this คือ copy ไม่ใช่ reference!
this.X += dx;
this.Y += dy;
}
}
ข้อจำกัดของ this
- ❌ ไม่สามารถใช้ใน
staticcontext (static methods, static constructors) - ❌ ไม่สามารถ assign ให้
this = somethingได้ (read-only) - ❌ ไม่สามารถใช้เป็น
ref/outparameter ได้ (ยกเว้น extension methods)
สรุป
this= อ้างอิงอินสแตนซ์ปัจจุบัน- ใช้หลัก 3 ทาง: (1) แยก Field/Parameter (2) Constructor Chaining (3) ส่งตัวเอง
- ใน Extension Methods:
this Type nameเป็นพารามิเตอร์แรก - ใน Struct: this คือ copy (value semantics)
- ไม่ใช้ได้ใน static context