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

ขอบเขตของตัวแปร (Scope) ใน C#


ภาพรวม

ขอบเขต (Scope) คือบริเวณของโค้ดที่ตัวแปรสามารถเข้าถึงได้ ใน C# มีระดับหลัก 2 ระดับ

1. ระดับเมธอด (Method Level / Local Variables)

  • ประกาศภายในเมธอด
  • เข้าถึงได้เฉพาะภายในเมธอดนั้น (และ nested scopes)
  • สิ้นสุดเมื่อเมธอดจบ

2. ระดับคลาส (Class Level / Fields / Member Variables)

  • ประกาศภายในคลาส แต่นอกเมธอด
  • เข้าถึงได้จากทุกเมธอดในคลาส (ขึ้นกับ access modifier)
  • อายุยืดตาม instance ของคลาส (instance fields) หรือตลอดโปรแกรม (static fields)

ตัวอย่างโค้ดเต็ม

using System;

namespace Demo
{
    class Program
    {
        // Class-level field (member variable)
        public int Divide(int num1, int num2)
        {
            // Method-level local variable
            int result = num1 / num2;
            return result;
        }

        static void Main(string[] args)
        {
            // Local variables in Main
            int a = 150;
            int b = 10;
            int res;
            Program p = new Program();
            res = p.Divide(a, b);
            Console.WriteLine("Division Result = {0}", res);
        }
    }
}

ผลลัพธ์

Division Result = 15

ขอบเขตเพิ่มเติม (Block Scope)

  • บล็อก { } (if, for, while, using, try) สร้าง scope ใหม่
  • ตัวแปรที่ประกาศในบล็อก เข้าถึงได้เฉพาะในบล็อกนั้น
  • ไม่สามารถประกาศตัวแปรชื่อซ้ำใน scope ตัวเดียวกันหรือ nested scope ได้