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

วิธีประกาศตัวแปร (Variables) ใน C#

ทุกตัวแปรใน C# มี Type เฉพาะ กำหนดขนาด Memory, ช่วงค่า และ Operation ที่ทำได้

Syntax

<data_type> <variable_list>;

ตัวอย่างประกาศพื้นฐาน

int x, y;           // หลายตัวแปร Type เดียวกัน
float z;            // Float
short p;            // Short
double salary;      // Double
char grade;         // Char
bool isActive;      // Boolean
string name;        // String (Reference Type)

ประกาศพร้อมกำหนดค่า (Initialization)

int score = 100;
float pi = 3.14f;        // ต้องมี f suffix
double precise = 3.14159;
decimal money = 19.99m;  // ต้องมี m suffix
char letter = 'A';
bool flag = true;
string message = "Hello";

Implicit Typing (var)

var count = 10;       // int
var price = 19.99;    // double
var name = "John";    // string
var isValid = true;   // bool

Constants (ค่าคงที่)

const double PI = 3.14159;
const int MAX_USERS = 100;
readonly int instanceId; // กำหนดได้ใน Constructor

Scope และ Lifetime

ประเภทScopeLifetime
Local Variableใน Block { } ที่ประกาศจบ Block ถูก Destroy
Field (Member Variable)ใน Class/Structอยู่ร่วมกับ Object Instance
Static Fieldใน Classอยู่ตลอดโปรแกรม

Naming Conventions (Microsoft Guidelines)

  • Local/Parameters: camelCase (e.g., userName)
  • Private Fields: _camelCase หรือ camelCase (e.g., _userName)
  • Constants: PascalCase หรือ UPPER_SNAKE_CASE
  • Public Properties/Methods: PascalCase