กลับไปหน้าบทความ

🟪 C# (สอนแบบครบระดับ)

C# เป็นภาษาใน ecosystem ของ .NET ใช้ทำแอป enterprise, web, desktop และเกม (Unity) ได้อย่างแข็งแกร่ง

📋 เนื้อหา (พื้นฐาน)

  • 🧭 C# คืออะไร
  • ⚙️ ติดตั้ง .NET
  • 🔤 ตัวแปรและชนิดข้อมูล
  • 🧮 เงื่อนไขและลูป
  • 🧩 Methods
  • 🏁 สรุป
  • 📝 แบบฝึกหัด

🧭 C# คืออะไร

ทำไมต้องเรียน C#?

C# เป็นภาษา OOP ที่ทำงานบน .NET runtime พัฒนาโดย Microsoft เป็นภาษาที่ทันสมัยและมีความสามารถครบถ้วน

  • • Type-safe: ตรวจสอบ type ตั้งแต่ compile
  • • OOP: Classes, Inheritance, Interfaces
  • • Modern: LINQ, async/await, pattern matching
  • • Cross-platform: Windows, Linux, macOS

C# ใช้ทำอะไร?

🌐 Web Development

ASP.NET Core, Blazor

🎮 Game Development

Unity Engine

🖥️ Desktop Apps

WPF, WinForms, MAUI

☁️ Cloud & APIs

Azure, Microservices

Hello World

// C# 10+ (Top-level statements)
Console.WriteLine("Hello, World!");

// แบบดั้งเดิม
namespace HelloApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

⚙️ ติดตั้ง .NET

ติดตั้ง .NET SDK

# ดาวน์โหลดจาก https://dotnet.microsoft.com/download

# ตรวจสอบ version
dotnet --version

# ดู SDK ที่ติดตั้ง
dotnet --list-sdks

สร้างและรันโปรเจกต์

# สร้าง console app
dotnet new console -n HelloApp
cd HelloApp

# รันโปรแกรม
dotnet run

# Build เป็น executable
dotnet build
dotnet publish -c Release

# Project types
dotnet new console    # Console App
dotnet new webapi     # Web API
dotnet new mvc        # MVC Web App
dotnet new classlib   # Class Library

🔤 ตัวแปรและชนิดข้อมูล

Basic Types

// Integer types
int age = 20;
long bigNum = 10000000000L;
short small = 100;
byte tiny = 255;

// Floating point
float f = 3.14f;
double d = 3.14159265;
decimal money = 99.99m;  // สำหรับการเงิน

// Boolean
bool isActive = true;

// Character & String
char grade = 'A';
string name = "Somchai";

// Nullable types
int? nullableInt = null;
string? nullableString = null;

var & const

// var - type inference
var x = 10;        // int
var y = 3.14;      // double
var s = "hello";   // string

// const - ค่าคงที่
const int MAX = 100;
const double PI = 3.14159;

// readonly - กำหนดได้ครั้งเดียว (ใน constructor)
readonly string _name;

// String interpolation
string greeting = $"Hello, {name}! Age: {age}";

// Verbatim strings
string path = @"C:\Users\file.txt";

🧮 เงื่อนไขและลูป

if-else & switch

int score = 85;

if (score >= 80)
    Console.WriteLine("Grade: A");
else if (score >= 70)
    Console.WriteLine("Grade: B");
else
    Console.WriteLine("Grade: C");

// Ternary operator
string result = score >= 50 ? "Pass" : "Fail";

// Switch expression (C# 8+)
string grade = score switch
{
    >= 80 => "A",
    >= 70 => "B",
    >= 60 => "C",
    _ => "F"
};

Loops

// for loop
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

// while loop
int count = 0;
while (count < 3)
{
    Console.WriteLine(count++);
}

// foreach
string[] names = { "John", "Jane", "Bob" };
foreach (var name in names)
{
    Console.WriteLine(name);
}

// LINQ-style iteration
names.ToList().ForEach(n => Console.WriteLine(n));

🧩 Methods

Method Declaration

// Basic method
static int Add(int a, int b)
{
    return a + b;
}

// Expression-bodied (C# 6+)
static int Multiply(int a, int b) => a * b;

// Optional parameters
static void Greet(string name, string greeting = "Hello")
{
    Console.WriteLine($"{greeting}, {name}!");
}

// Named arguments
Greet(greeting: "Hi", name: "John");

// params array
static int Sum(params int[] numbers)
{
    return numbers.Sum();
}
Sum(1, 2, 3, 4, 5);

ref, out, in

// ref - pass by reference (must be initialized)
static void Double(ref int x)
{
    x *= 2;
}

int num = 5;
Double(ref num);  // num = 10

// out - output parameter (doesn't need init)
static bool TryParse(string s, out int result)
{
    return int.TryParse(s, out result);
}

if (TryParse("123", out int value))
    Console.WriteLine(value);

🏁 สรุป

  • ✅ C# เป็นภาษา type-safe ที่ทำงานบน .NET
  • ✅ ใช้ dotnet CLI สร้างและจัดการโปรเจกต์
  • ✅ รองรับ modern features: var, switch expression
  • ✅ String interpolation ($) ช่วยจัดการ string

📝 แบบฝึกหัด

Variables

  1. ประกาศตัวแปรเก็บชื่อ, อายุ, เงินเดือน
  2. ใช้ string interpolation แสดงข้อมูล

Control Flow

  1. เขียนโปรแกรมตัดเกรดด้วย switch expression
  2. วนลูปพิมพ์เลขคู่ 2-20