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

ตัวแปรส่วนตัว (Private Variables/Fields) ใน C#

private Access Modifier ใช้ซ่อน Field/Variable ไว้ภายในคลาสเท่านั้น เป็นพื้นฐานของ Encapsulation — ควบคุมการเข้าถึงผ่าน Public Methods/Properties แทน

ลักษณะ

  • เข้าถึงได้เฉพาะในคลาสที่ประกาศ
  • Instance ภายนอกเรียกไม่ได้ (Compile Error)
  • Derived Class เรียกไม่ได้ (ใช้ protected แทนถ้าต้องการ)

ตัวอย่าง: Encapsulation กับ Private Fields

using System;

namespace BoxApplication {
    class Box {
        // Private fields - ซ่อนข้อมูลภายใน
        private double _length;
        private double _breadth;
        private double _height;
        
        // Public methods - จุดเข้าถึงที่ควบคุมได้
        public void SetLength(double len) {
            if (len <= 0) throw new ArgumentException("Length must be positive");
            _length = len;
        }
        
        public void SetBreadth(double bre) {
            if (bre <= 0) throw new ArgumentException("Breadth must be positive");
            _breadth = bre;
        }
        
        public void SetHeight(double hei) {
            if (hei <= 0) throw new ArgumentException("Height must be positive");
            _height = hei;
        }
        
        public double GetVolume() => _length * _breadth * _height;
    }
    
    class BoxTester {
        static void Main() {
            Box box1 = new Box();
            // box1._length = 10; // ❌ Compile Error: inaccessible
            
            box1.SetLength(6.0);
            box1.SetBreadth(7.0);
            box1.SetHeight(5.0);
            
            Console.WriteLine("Volume: " + box1.GetVolume()); // 210
            Console.ReadKey();
        }
    }
}

Modern C#: ใช้ Properties แทน Fields

แทน Private Field + Getter/Setter ให้ใช้ Auto-implemented Properties:

public class Box {
    // Private setter = เขียนได้แค่ในคลาส, อ่านได้จากนอก
    public double Length { get; private set; }
    public double Breadth { get; private set; }
    public double Height { get; private set; }
    
    public double Volume => Length * Breadth * Height;
    
    public Box(double length, double breadth, double height) {
        Length = length;
        Breadth = breadth;
        Height = height;
    }
}

Private Constants / Readonly Fields

class Config {
    private const string DefaultConnectionString = "Server=localhost;"; // Compile-time constant
    private readonly string _instanceId; // Runtime constant, set ใน Constructor
    
    public Config() {
        _instanceId = Guid.NewGuid().ToString();
    }
}

Best Practices

  • Default ไปที่ private — เปิดเผยเฉพาะเมื่อจำเป็น
  • ใช้ Properties แทน Public Fields — ควบคุม Validation, Logging, Lazy loading ได้
  • ตั้งชื่อ Private Fields ด้วย _camelCase (convention)
  • หลีกเลี่ยง public Fields — ลงนามสัญญา Interface ไม่ได้ และควบคุมการเปลี่ยนแปลงไม่ได้