Software Engineer Encyclopedia
0%
Domain 02 · Advanced C# and .NET · Topic 2.1 · Part 1/3

C# الجزء 1: نظام الأنواع والـ OOP واللغة الحديثة

C# — Part 1: Type System, OOP and Modern Language Features

الأساس اللي كل كود .NET بيتبني عليه: إزاي الـ C# بيتحوّل لـ IL وبيتنفّذ، الفرق الحقيقي بين Value و Reference Types، الـ Classes والـ OOP والـ polymorphism من جوه، Interfaces مقابل Abstract Classes، الـ Nullable Reference Types، الـ Strings، الـ Records والـ Pattern Matching، والمميزات الحديثة (C# 12 لـ C# 14).

  • Foundation → Intermediate
  • ~30 min read
  • 17 sections
  • 27 code examples
  • 3 diagrams
  • 13 questions
  • Priority L1 · Essential
  • .NET 10 LTS · C# 14

المتطلبات قبل ما تبدأ

  • مفيش متطلبات C# سابقة: أول تلات أقسام بيبدأوا من الصفر.
  • مفيد تكون كتبت كود بأي لغة قبل كده (متغير، شرط، loop) — لكن مش شرط.
  • .NET SDK متثبت عشان تشغّل الأمثلة (dotnet --version).

مستوى التعمق المطلوب

DEEPOOP, generics, collections, LINQ, async/await, exceptions, and SOLID.

01

C#‎ من الصفر (1): أول برنامج، المتغيرات، والأنواع

Start here if you have never written C#: program structure, variables, types, strings, conversions
Basics
القسم ده لمين؟

لو دي أول مرة تكتب C#‎، ابدأ من هنا: التلات أقسام الجايين بيبنوا الأساس (متغيرات، شروط، loops، collections، methods، أول class) بمثال واحد بيكبر معاك. لو عندك الأساسيات دي، اقفز لقسم «الـ C#‎ والـ CLR ونظام الأنواع» — باقي الدرس بيشرح اللي بيحصل تحت الحاجات دي.

حالة التحقق

أكواد C#‎ في الأقسام دي لم يتم عمل compile لها في بيئة تجهيز الموسوعة (الـ ‎.NET SDK مش متاح هناك). هي مكتوبة على C#‎ حديث (‎.NET 8 وأحدث). اكتبها بإيدك وشغّلها — ده جزء من التعلّم، ولو لقيت خطأ فالـ compiler هيقولك مكانه بالظبط.

شغّل أول برنامج

BashCreate and run a console project
dotnet new console -n FirstSteps
cd FirstSteps
dotnet run

الأمر الأول بيعمل فولدر فيه ملفين مهمين: FirstSteps.csproj (إعدادات المشروع) و Program.cs (الكود). افتح Program.cs وامسح اللي فيه واكتب:

C#Program.cs — top-level statements: the file IS the program
Console.WriteLine("Welcome to the grade book");

Console.Write("Student name: ");
string? name = Console.ReadLine();          // string? = "a string, or null if there was no input"

Console.WriteLine($"Hello, {name}!");        // $"..." is string interpolation: {name} is replaced by its value

مفيش class Program ولا static void Main؟ موجودين، لكن الـ compiler بيولّدهم لك. دي اسمها top-level statements: الملف نفسه هو البرنامج، وبيتنفذ من أول سطر لآخر سطر. كل جملة بتنتهي بـ ;، والـ C#‎ حساسة لحالة الحروف: Console غير console.

المتغيرات: اسم + نوع + قيمة

المتغير صندوق له اسم. في C#‎ كل صندوق له نوع ثابت بيحدد إيه اللي ينفع يتحط فيه — وده بيتفحص قبل ما البرنامج يشتغل (compile time)، فأخطاء كتير بتتمسك قبل ما المستخدم يشوفها.

C#The types you will use 95% of the time
int age = 21;                    // whole numbers (about ±2 billion)
long population = 8_100_000_000; // bigger whole numbers; _ is just a visual separator
double average = 87.5;           // fractional numbers: fast, but NOT exact (0.1 + 0.2 != 0.3)
decimal price = 199.99m;         // exact decimal arithmetic: ALWAYS use this for money (note the m suffix)
bool passed = true;              // true or false
char grade = 'A';                // ONE character, single quotes
string city = "Cairo";           // text, double quotes

var count = 10;                  // var = "compiler, work out the type from the right-hand side" -> int
// var x;                        // error: nothing to infer the type from
// count = "ten";                // error: count is an int forever

const double PassMark = 50.0;    // a value that can never change
عايز تخزّنالنوعملاحظة
عدد صحيح (عدّاد، عمر، كمية)intلو ممكن يعدّي 2 مليار: long
فلوسdecimalمش double أبدًا — الـ double بيقرّب
قياس علمي / متوسط / نسبةdoubleسريع، تقريبي
نعم/لاbool
نصstringimmutable: أي «تعديل» بيعمل string جديد

العمليات والتحويل بين الأنواع

C#Arithmetic surprises and safe conversion
int a = 7, b = 2;
Console.WriteLine(a / b);          // 3   <- int / int throws away the fraction!
Console.WriteLine(a / 2.0);        // 3.5 <- one double makes the whole division double
Console.WriteLine(a % b);          // 1   <- remainder
Console.WriteLine((double)a / b);  // 3.5 <- a cast: "treat a as a double here"

string input = "42";
int number = int.Parse(input);     // works, but THROWS an exception if input is "abc"

if (int.TryParse(Console.ReadLine(), out int score))   // the safe way: returns false instead of throwing
{
    Console.WriteLine($"You typed {score}; doubled it is {score * 2}");
}
else
{
    Console.WriteLine("That was not a whole number.");
}

string text = score.ToString();                  // anything -> string
Console.WriteLine($"{87.456:F1}");               // 87.5   format: 1 digit after the point
Console.WriteLine($"{1234.5m:C}");               // currency, formatted for the current culture

أشهر مفاجأتين للمبتدئ: 7 / 2 بتدّي 3 مش 3.5 (قسمة أعداد صحيحة)، و int.Parse بتوقّع البرنامج لو المستخدم كتب حروف. أي حاجة جاية من المستخدم أو ملف أو شبكة: استخدم TryParse.

out int score: الـ method بترجّع bool (نجحت ولا لأ) وبتحط الرقم في المتغير score. نمط هتشوفه كتير في ‎.NET.

02

C#‎ من الصفر (2): الشروط، التكرار، والـ Collections

if / switch, loops, arrays, List and Dictionary — with the mistakes everyone makes once
Basics

القرارات

C#if / else, comparison and logical operators, switch expression
double mark = 73.5;

if (mark >= 85)
{
    Console.WriteLine("Excellent");
}
else if (mark >= 50)
{
    Console.WriteLine("Passed");
}
else
{
    Console.WriteLine("Failed");
}

// ==  equal      !=  not equal      &&  and      ||  or      !  not
bool honours = mark >= 85 && mark <= 100;

// The same decision as a switch EXPRESSION: it produces a value, and the compiler warns if a case is missing
string letter = mark switch
{
    >= 85 => "A",
    >= 75 => "B",
    >= 65 => "C",
    >= 50 => "D",
    _     => "F"          // _ means "anything else"
};
Console.WriteLine($"Grade: {letter}");
غلطة هتعملها مرة واحدة

= للإسناد و == للمقارنة. if (x = 5) مش بيتعمله compile في C#‎ (على عكس C)، فالـ compiler هيمسكها — لكن if (isReady = true) هيعدّي ويبقى دايمًا true. اكتب if (isReady).

التكرار

C#for, foreach, while — and when to use which
for (int i = 1; i <= 5; i++)                 // you need the counter
{
    Console.WriteLine($"Attempt {i}");
}

string[] subjects = ["Math", "Physics", "Programming"];   // an array: fixed size
foreach (string subject in subjects)        // you need each item, not its position: prefer this
{
    Console.WriteLine(subject);
}

int tries = 0;
while (true)                                // you do not know in advance how many rounds
{
    Console.Write("Enter a mark between 0 and 100: ");
    if (double.TryParse(Console.ReadLine(), out double m) && m is >= 0 and <= 100)
    {
        Console.WriteLine($"Accepted after {tries + 1} tries.");
        break;                              // leave the loop
    }
    tries++;
}

الـ Collections: لما متغير واحد مش كفاية

C#
 and Dictionary<TKey, TValue>">
double[] fixedMarks = [70, 85.5, 92];       // array: size decided once
Console.WriteLine(fixedMarks[0]);           // 70  <- indexes start at 0
Console.WriteLine(fixedMarks.Length);       // 3
// fixedMarks[3] = 1;                       // IndexOutOfRangeException at run time: valid indexes are 0..2

List<double> marks = [70, 85.5];            // List<T>: grows and shrinks — your default collection
marks.Add(92);
marks.Remove(70);
Console.WriteLine(marks.Count);             // 2
Console.WriteLine(marks.Average());         // 88.75  (LINQ: needs `using System.Linq;` — on by default in new projects)
Console.WriteLine(marks.Max());

Dictionary<string, double> byStudent = new()        // key -> value lookup
{
    ["Mona"] = 91,
    ["Omar"] = 67.5
};
byStudent["Sara"] = 78;                             // add or overwrite
Console.WriteLine(byStudent["Mona"]);               // 91
// Console.WriteLine(byStudent["Zed"]);             // KeyNotFoundException

if (byStudent.TryGetValue("Zed", out double zedMark))   // the safe lookup
    Console.WriteLine(zedMark);
else
    Console.WriteLine("No such student.");

foreach (var (student, value) in byStudent)         // each entry is a key/value pair
    Console.WriteLine($"{student}: {value}");
السؤالاستخدم
قائمة عناصر بترتيب، وعددها بيتغيرList<T>
عدد ثابت معروف مسبقًا (أيام الأسبوع، matrix)array T[]
«هات القيمة بتاعة المفتاح ده» بسرعةDictionary<TKey, TValue>
«العنصر ده موجود ولا لأ؟» من غير تكرارHashSet<T>

ليه الـ Dictionary أسرع من البحث في List، وإيه معنى <T> بالتفصيل: ده موضوع الـ Generics والـ Collections في Part 2.

03

C#‎ من الصفر (3): Methods، أول Class، والأخطاء

Naming a piece of logic, grouping data with behaviour, and handling failure
Basics

Methods: اسم لقطعة منطق

لما نفس الحسبة تتكرر، أو لما جزء من الكود يستاهل اسم، حطّه في method. الـ method بتاخد parameters وبترجّع قيمة (أو void لو مش بترجّع حاجة).

C#Methods in a top-level program are written as local functions
double average = Average([70, 85.5, 92]);
Console.WriteLine($"Average {average:F1} -> {ToLetter(average)}");
PrintLine();                                        // uses the default value
PrintLine('=', 30);

static double Average(List<double> marks)           // return type, name, parameters
{
    if (marks.Count == 0)
        return 0;                                   // guard clause: handle the odd case first, then the main path
    double sum = 0;
    foreach (double m in marks)
        sum += m;
    return sum / marks.Count;
}

static string ToLetter(double mark) => mark switch  // expression-bodied: one expression, no braces
{
    >= 85 => "A", >= 75 => "B", >= 65 => "C", >= 50 => "D", _ => "F"
};

static void PrintLine(char symbol = '-', int width = 20)   // void = returns nothing; parameters can have defaults
{
    Console.WriteLine(new string(symbol, width));
}

أول Class: بيانات وسلوك مع بعض

لحد دلوقتي الطالب عندنا اسم في متغير ودرجات في متغير تاني. الـ class بيجمعهم في نوع واحد جديد إنت اللي بتعرّفه، ومعاهم العمليات اللي ليها معنى عليهم.

C#Student.cs — put each class in its own file
public class Student
{
    private readonly List<double> _marks = [];      // private: only code inside this class can touch it

    public Student(string name)                     // constructor: runs when you write `new Student(...)`
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("A student needs a name.", nameof(name));
        Name = name;
    }

    public string Name { get; }                     // property with only a getter: set once, in the constructor
    public int MarkCount => _marks.Count;           // computed property
    public double Average => _marks.Count == 0 ? 0 : _marks.Average();

    public void AddMark(double mark)
    {
        if (mark is < 0 or > 100)
            throw new ArgumentOutOfRangeException(nameof(mark), mark, "A mark must be between 0 and 100.");
        _marks.Add(mark);
    }
}
C#Program.cs — using the class, and handling failure
var students = new Dictionary<string, Student>(StringComparer.OrdinalIgnoreCase);   // "mona" and "Mona" are the same key

while (true)
{
    Console.Write("name mark (or 'done'): ");
    string? line = Console.ReadLine();
    if (line is null || line.Trim() == "done")
        break;

    string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
    if (parts.Length != 2 || !double.TryParse(parts[1], out double mark))
    {
        Console.WriteLine("Please type a name, a space, then a number. Example: Mona 87.5");
        continue;                                   // skip to the next round of the loop
    }

    try
    {
        if (!students.TryGetValue(parts[0], out Student? student))
        {
            student = new Student(parts[0]);
            students[parts[0]] = student;
        }
        student.AddMark(mark);
    }
    catch (ArgumentOutOfRangeException ex)          // catch the SPECIFIC failure you know how to handle
    {
        Console.WriteLine($"Rejected: {ex.Message}");
    }
}

Console.WriteLine();
foreach (Student s in students.Values.OrderByDescending(s => s.Average))
    Console.WriteLine($"{s.Name,-12} {s.MarkCount} mark(s)   average {s.Average,6:F1}");

ليه _marks private؟ عشان مفيش كود برا الـ class يقدر يحط درجة 500 أو يمسح الليست. الطريق الوحيد لإضافة درجة هو AddMark اللي بتتحقق. ده اسمه encapsulation: الـ object مسؤول عن إن حالته تفضل صحيحة — وهتلاقي شرحه الكامل في قسم الـ Encapsulation بعد شوية.

throw و try/catch: الـ Student ما يعرفش هو شغال في console ولا في web API، فما ينفعش يطبع رسالة. بيرمي exception بيقول «ده غلط»، واللي نادى عليه هو اللي يقرر يعمل إيه. امسك النوع المحدد اللي تعرف تتصرف معاه؛ catch (Exception) العام بيخبّي أخطاء المفروض تشوفها.

للمدخلات المتوقع إنها تغلط (المستخدم كتب حروف): TryParse و if، مش exceptions. الـ exception للحالة اللي المفروض ما تحصلش.

تفاصيل صغيرة: {s.Name,-12} بيحاذي الاسم في 12 خانة ناحية الشمال؛ Student? معناها «ممكن يكون null»، والـ compiler بيتابعها معاك (ده الـ nullable reference types — له قسم في الدرس).

تمارين قبل ما تكمّل

  • Beginner: ضيف للبرنامج أمر list بيطبع كل الطلبة من غير ما يخرج.
  • Beginner: ضيف في Student property اسمها Highest بترجّع أعلى درجة (وخد بالك من حالة مفيش درجات).
  • Intermediate: خلّي الحد الأقصى للدرجات 5 لكل طالب: AddMark ترمي InvalidOperationException لو اتعدّى، والبرنامج يمسكها ويطبع رسالة واضحة.
  • Intermediate: اطبع في الآخر عدد الناجحين (متوسط ≥ 50) ونسبتهم — وخد بالك من قسمة الأعداد الصحيحة.
  • Challenge: احفظ البيانات في ملف نصي عند الخروج واقراها عند التشغيل (File.WriteAllLines / File.ReadAllLines). إيه اللي هيحصل لو الملف مش موجود أو فيه سطر بايظ؟

المستخدم هيكتب سعر منتج. أنهي سطر صح؟

04

الـ C#‎ والـ CLR ونظام الأنواع

C# fundamentals · compilation, CLR and the type system
Basics

الـ C#‎ لغة statically typed: نوع كل متغير بيتحدد وقت الـ compile، والمترجم بيرفض الأخطاء قبل ما الكود يشتغل. والكود اللي بتكتبه مش بيتنفّذ مباشرة؛ بيمر بمرحلتين.

SourceProgram.cs RoslynC# compiler AssemblyIL + metadata (.dll) CLR + JITload · verify Nativemachine code
C#‎ بيتترجم أولاً لـ IL (لغة وسيطة) محفوظة في assembly، وبعدين الـ CLR بيحمّلها والـ JIT بيحوّل كل method لكود الجهاز أول مرة بتتنادى. عشان كده نفس الـ dll بيشتغل على Windows و Linux و macOS.
  • CTS (Common Type System): العقد اللي بيعرّف الأنواع (class, struct, interface, enum, delegate) وبيخلّي لغات ‎.NET المختلفة تتفاهم. كلمات C#‎ زي int و string مجرد أسماء بديلة لأنواع الـ BCL (System.Int32 و System.String).
  • Assembly: وحدة النشر (dll أو exe) فيها الـ IL والـ metadata.
  • Top-level statements: من C#‎ 9 مش لازم تكتب class Program و Main في ملف الدخول؛ المترجم بيولّدهم.
keywordالنوع في ‎.NETالحجمملاحظة
int / longInt32 / Int644 / 8 bytesالـ integer arithmetic بتلف (wrap) عند الـ overflow افتراضياً
double / floatDouble / Single8 / 4binary floating point: مش دقيق للكسور العشرية
decimalDecimal16base-10: للفلوس. أبطأ من double
bool / charBoolean / Char1 / 2char هو UTF-16 code unit مش «حرف» دايماً
stringStringreferenceimmutable (هنرجعله في قسم الـ Strings)
objectObjectreferenceجذر كل الأنواع
C#Program.cs (top-level statements)
int count = 42;                    // Int32
long big = 3_000_000_000L;         // digit separators; 'L' suffix = long
double d = 0.1 + 0.2;              // binary floating point
decimal m = 0.1m + 0.2m;           // base-10 floating point (money)
bool flag = true;
char letter = 'A';                 // one UTF-16 code unit
string name = "Ahmed";
var inferred = 3.5;                // 'var' = compiler infers double. Still statically typed!

Console.WriteLine($"{count} {big} {flag} {letter} {name} {inferred.GetType()}");

Console.WriteLine(d == 0.3);       // False: 0.1 and 0.2 have no exact binary form
Console.WriteLine(m == 0.3m);      // True
Console.WriteLine(7 / 2);          // 3    integer division truncates
Console.WriteLine(7 / 2.0);        // 3.5  one operand is double

int max = int.MaxValue;
Console.WriteLine(unchecked(max + 1));         // -2147483648 (wraps around silently)
try { Console.WriteLine(checked(max + 1)); }   // checked context throws instead
catch (OverflowException) { Console.WriteLine("overflow detected"); }

الشرح وتتبّع التنفيذ

  1. مفيش Main: المترجم بيولّد Program.Main ويحط الجمل دي جواه. التنفيذ بيبدأ من أول سطر.
  2. var مش «dynamic»: النوع double اتحدد وقت الـ compile، وناتج GetType() هو System.Double. استخدمه لما النوع واضح من الطرف اليمين.
  3. 0.1 + 0.2 == 0.3 بـ false لأن 0.1 مش ممكن يتمثّل بدقة في الـ binary (زي 1/3 في العشري). لهذا للفلوس استخدم decimal، ولمقارنة double استخدم tolerance.
  4. int.MaxValue + 1 بيرجع قيمة سالبة في السياق الافتراضي (unchecked) عشان الأداء. لو الـ overflow خطر (حسابات مالية، أطوال) استخدم checked أو فعّل <CheckForOverflowUnderflow> في الـ csproj.
  5. الناتج المتوقع بالترتيب: 42 3000000000 True A Ahmed System.Double ثم False, True, 3, 3.5, -2147483648, overflow detected.
const مقابل readonly

const قيمة معروفة وقت الـ compile ومتحطوطة (inlined) في كل مكان بتتستخدم فيه، فلو غيّرتها في library لازم تعيد compile كل اللي بيستخدمها. readonly field بتتحدد وقت التشغيل (في constructor)، وأأمن للقيم اللي ممكن تتغيّر بين الإصدارات.

05

Value Types مقابل Reference Types

Value types vs reference types · copy semantics · boxing
Deep dive

ده أهم تمييز في النظام كله. السؤال: «لما أعمل b = a، إيه اللي بيتنسخ؟»

Value Type (struct, enum, int, bool, DateTime)

المتغير بيحتوي القيمة نفسها. التعيين والتمرير كـ argument بينسخوا القيمة كلها، فالنسختين مستقلتين.

Reference Type (class, interface, delegate, string, array)

المتغير بيحتوي مرجع (reference) لـ object على الـ heap. التعيين بينسخ المرجع بس، فالاتنين بيشاوروا على نفس الـ object.

Value type (struct) s1X = 1 · Y = 2 s2 = s1X = 99 · Y = 2 (copy, changed) s1 stays 1: two independent values Reference type (class) c1 c2 Heap objectX = 99 · Y = 2one shared instance c1.X is 99 after c2.X = 99
نفس الكود لـ struct و class. متغيرات الـ struct بتحتوي البيانات مباشرة فكل نسخة مستقلة، أما متغيرات الـ class فهي مراجع لـ object واحد في الـ heap.
C#Copy semantics, and what passing an argument really does
PointStruct s1 = new(1, 2);
PointStruct s2 = s1;          // copies the whole value
s2.X = 99;
Console.WriteLine(s1.X);      // 1   - s1 unaffected

PointClass c1 = new(1, 2);
PointClass c2 = c1;           // copies only the reference
c2.X = 99;
Console.WriteLine(c1.X);      // 99  - same object

// A reference is passed BY VALUE: the callee gets a copy of the reference.
static void Reset(PointClass p)
{
    p.X = 0;                  // follows the copy of the reference -> mutates the shared object
    p = new PointClass(5, 5); // rebinds only the local copy; the caller does not see this
}
static void ResetRef(ref PointClass p)
{
    p = new PointClass(5, 5); // 'ref' passes the variable itself, so the caller's variable changes
}

Reset(c1);
Console.WriteLine(c1.X);      // 0   - mutation visible, rebinding not
ResetRef(ref c1);
Console.WriteLine(c1.X);      // 5   - the caller's variable now points to the new object

struct PointStruct { public int X, Y; public PointStruct(int x, int y) { X = x; Y = y; } }
class PointClass   { public int X, Y; public PointClass(int x, int y) { X = x; Y = y; } }

الشرح

  1. سطر s2 = s1 بينسخ 8 bytes (حقلين int). تعديل s2.X مفيش له تأثير على s1.
  2. سطر c2 = c1 بينسخ المرجع بس؛ فيه object واحد، ولما عدّلنا c2.X شفنا التعديل من c1.
  3. في Reset: الـ p نسخة من المرجع. p.X = 0 بيغيّر الـ object المشترك (فبيتشاف برا). لكن p = new ... بيغيّر النسخة المحلية بس. ده بيوضح إن «C#‎ بيمرّر كل حاجة by value» وإن الـ value ممكن تكون مرجع.
  4. ref بيمرّر المتغير نفسه، فتعيين p جواه بيغيّر متغير المُنادي.

فين بتتخزّن القيم؟

الشائع «value types على الـ stack و reference types على الـ heap» تبسيط. الصح: متغير value type بيخزّن بياناته حيث ما هو معرّف. لو local variable فغالباً على الـ stack (أو في register)، لكن لو هو حقل جوه class فهو جزء من الـ object على الـ heap، ولو اتلقط في lambda أو async method بيتنقل للـ heap. أما الـ reference types فالـ object دايماً على الـ heap (والمرجع نفسه قيمة 8 bytes). الفرق العملي اللي يهمّك هو الـ copy semantics وتكلفة الـ allocation والـ GC.

Boxing و Unboxing

لما تحط value type في متغير object أو interface، الـ runtime بيعمل box: بيحجز object على الـ heap وبينسخ القيمة فيه. ده allocation حقيقي بيضغط على الـ GC.

C#Boxing allocates; the box is an independent copy
int n = 42;
object boxed = n;                 // BOXING: heap allocation + copy of 42
n = 100;
Console.WriteLine(boxed);         // 42   the box did not change
int back = (int)boxed;            // UNBOXING: type check, then copy out
Console.WriteLine(back);          // 42

try { long wrong = (long)boxed; } // the box holds an Int32, not an Int64
catch (InvalidCastException) { Console.WriteLine("unbox must match the exact type"); }

IComparable c = n;                // hidden boxing: assigning a struct to an interface variable

أماكن الـ boxing المخفية: تمرير struct لـ parameter من نوع object، أو استدعاء ToString()/interface method على struct مش بيطبّقها صح، أو الـ collections القديمة (ArrayList). الـ generics (List<int>) بتحل المشكلة (قسم الـ Generics في الجزء 2).

إمتى struct؟

القاعدة التقليدية من Framework Design Guidelines: تجنّب الـ struct إلا لو النوع بيمثّل قيمة واحدة منطقياً زي الأرقام، وحجمه أقل من حوالي 16 byte، وimmutable، ومش هيتعمله boxing كتير. غير كده استخدم class. لو struct كبير لازم تمرره بـ in أو ref readonly عشان تتجنب النسخ، وعلّم النوع readonly struct عشان المترجم ميعملش «defensive copies» لما تنادي عليه عن طريق in.

06

الـ Classes والـ Objects

Classes and objects · members, constructors, access modifiers
Practical

الـ class هو القالب (state + behavior)، والـ object هو instance منه على الـ heap. العناصر: fields (البيانات الخام)، properties (واجهة محكومة للبيانات)، methods، constructors، وstatic members (بتخص النوع نفسه مش instance).

C#BankAccount.cs
public class BankAccount
{
    private static int _nextId = 1000;         // static: one copy shared by ALL instances
    private decimal _balance;                  // instance field, hidden from outside

    public int Id { get; }                     // get-only auto-property: assignable only in the constructor
    public string Owner { get; }
    public decimal Balance => _balance;        // expression-bodied read-only property

    public BankAccount(string owner, decimal openingBalance = 0m)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(owner);
        ArgumentOutOfRangeException.ThrowIfNegative(openingBalance);

        Id = ++_nextId;
        Owner = owner;
        _balance = openingBalance;
    }

    public void Deposit(decimal amount)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
        _balance += amount;
    }

    public bool TryWithdraw(decimal amount)
    {
        if (amount <= 0 || amount > _balance) return false;   // business rule enforced HERE
        _balance -= amount;
        return true;
    }

    public override string ToString() => $"#{Id} {Owner}: {_balance:N2}";
}

// ---- Program.cs (usage) ----
var acc = new BankAccount("Mona", 500m);
acc.Deposit(250m);
Console.WriteLine(acc.TryWithdraw(1000m));   // False  (insufficient funds)
Console.WriteLine(acc);                      // #1001 Mona: 750.00

الشرح وتتبّع التنفيذ

  1. new BankAccount("Mona", 500m): الـ runtime بيحجز object على الـ heap بحقوله على الـ default، بعدين بينفّذ الـ constructor. الـ guard clauses في الأول بترفض البيانات الغلط قبل ما الـ object يتكوّن (مفيش object نص مبني).
  2. ++_nextId بيزوّد العداد المشترك ويرجع 1001، فـ Id = 1001.
  3. الـ _balance private، والـ Balance للقراءة بس. الطريقة الوحيدة لتغيير الرصيد هي Deposit/TryWithdraw اللي بيحافظوا على الـ invariant «الرصيد مش بيبقى سالب». ده Encapsulation الحقيقي: الحماية للـ invariants مش مجرد إخفاء الحقول.
  4. الناتج: 500 + 250 = 750، السحب 1000 مرفوض فـ False.
Modifierالرؤية
publicأي كود
privateجوه النوع نفسه فقط (الافتراضي لأعضاء الـ class)
protectedالنوع والأنواع المشتقة منه
internalنفس الـ assembly (الافتراضي للأنواع غير المتداخلة)
protected internal / private protectedاتحاد / تقاطع protected و internal
file (C#‎ 11)نفس ملف المصدر فقط

قاعدة: ابدأ بأضيق visibility ممكنة ووسّعها عند الحاجة. وبراهن إن static state القابل للتغيير (زي _nextId هنا) مش thread-safe؛ في تطبيق متعدد الـ threads استخدم Interlocked.Increment (هنشرحه في الجزء 3).

07

Encapsulation و Inheritance و Polymorphism و Abstraction

The four OOP pillars · virtual dispatch · constructor order
Deep dive

Encapsulation

إخفاء الحالة الداخلية وإتاحتها عبر واجهة بتحمي الـ invariants (شفنا في BankAccount).

Inheritance

علاقة «is-a»: النوع المشتق بياخد أعضاء الأساس ويضيف أو يعدّل. C#‎ بتدعم وراثة class واحد فقط (وكتير interfaces).

Polymorphism

التعامل مع أنواع مختلفة من خلال نفس الواجهة، والسلوك الفعلي بيتحدد حسب النوع وقت التشغيل.

Abstraction

تعريف «إيه المطلوب» من غير «إزاي» (abstract members و interfaces).

C#Shapes.cs: inheritance, abstract, virtual, override
public abstract class Shape
{
    public string Name { get; }
    protected Shape(string name)
    {
        Name = name;
        Console.WriteLine($"Shape ctor ({name})");
    }

    public abstract double Area();                                  // no body: derived MUST implement
    public virtual string Describe() => $"{Name} with area {Area():F2}";   // default, may be overridden
}

public sealed class Circle : Shape
{
    private readonly double _r;
    public Circle(double r) : base("Circle")                        // base ctor runs FIRST
    {
        _r = r;
        Console.WriteLine("Circle ctor");
    }
    public override double Area() => Math.PI * _r * _r;
}

public class Rectangle : Shape
{
    public double W { get; }
    public double H { get; }
    public Rectangle(double w, double h) : base("Rectangle") { W = w; H = h; }
    public override double Area() => W * H;
    public override string Describe() => $"{base.Describe()} ({W}x{H})";   // extend, don't replace
}

// ---- Program.cs (usage) ----
Shape[] shapes = { new Circle(2), new Rectangle(3, 4) };
foreach (Shape s in shapes)
    Console.WriteLine(s.Describe());

الشرح وتتبّع التنفيذ

  1. Shape abstract: مينفعش new Shape(...). الـ constructor بتاعه protected عشان المشتقات بس هي اللي تنادي عليه.
  2. أثناء تكوين الـ array: new Circle(2) ⇐ يتنفّذ Shape ctor الأول (Shape ctor (Circle)) وبعدين جسم Circle ctor (Circle ctor). بعدها new Rectangle(3,4) ⇐ Shape ctor (Rectangle). الأساس بيتبني قبل المشتق دايماً.
  3. في الـ foreach: المتغير s نوعه الثابت Shape، لكن s.Describe() بيشغّل النسخة المناسبة للـ object الفعلي. للدائرة: Circle with area 12.57. للمستطيل: Rectangle with area 12.00 (3x4) (استخدم base.Describe() وأضاف عليه).
  4. sealed على Circle بيمنع الوراثة منه: بيدّي المترجم والـ JIT فرصة لتحسينات (devirtualization) ويقفل تصميمك للتغيير غير المقصود.
Shape sstatic type: Shape ref Circle object (heap)_r = 2type handle → Circle's table Circle method tableArea() → Circle.AreaDescribe() → Shape.DescribeToString() → Object.ToString s.Describe() → Shape.Describe → calls virtual Area() → looked up again → Circle.Area Cost: one extra indirection per virtual call (tiny; sealed/devirtualization can remove it)
الـ Virtual Dispatch: المترجم بيشوف النوع الثابت (Shape) ويعرف إن Area virtual. وقت التشغيل الـ CLR بيدور في method table بتاعة النوع الفعلي للـ object فيلاقي Circle.Area.

override مقابل new (الفرق اللي بيتسأل عليه في الإنترفيو)

C#override replaces the slot; new only hides the name
class Base
{
    public virtual string Who()   => "Base.Who";
    public string Hidden()        => "Base.Hidden";
}
class Derived : Base
{
    public override string Who()  => "Derived.Who";     // overrides the virtual slot
    public new string Hidden()    => "Derived.Hidden";  // hides: a NEW, unrelated method
}

// ---- Program.cs (usage) ----
Base b = new Derived();
Console.WriteLine(b.Who());               // Derived.Who    - runtime type decides
Console.WriteLine(b.Hidden());            // Base.Hidden    - static type decides
Console.WriteLine(((Derived)b).Hidden()); // Derived.Hidden

new بيكسر الـ polymorphism: نفس الـ object بيدّي نتيجة مختلفة حسب نوع المتغير اللي بتناديه منه. استخدمه نادراً (عادةً لما بتتعامل مع library مش بتتحكم فيها).

ما تنادّيش virtual method من constructor

في Base() لو نادّيت Who() (virtual)، النسخة المشتقة هتتنفّذ قبل ما constructor المشتق يخلص، يعني حقوله لسه على الـ default (null أو 0). ده مصدر bugs غريبة. ابعد عن ده.

Composition over Inheritance: الوراثة بتربط المشتق بتفاصيل الأساس (fragile base class). لو العلاقة مش «is-a» حقيقية، ركّب الـ object من أجزاء (حقول من نوع interface) بدل ما ترث. ده مرتبط بقوة بمبدأ Liskov Substitution.

08

الـ Interfaces مقابل الـ Abstract Classes

Interfaces vs abstract classes · default interface methods
Deep dive

الاتنين بيعرّفوا عقد من غير تنفيذ كامل، لكن لهم أدوار مختلفة:

InterfaceAbstract class
الغرض«النوع ده بيقدر يعمل X» (capability / contract)«النوع ده هو نوع من X» ومعاه تنفيذ مشترك
الوراثةالـ class يطبّق أي عدد من الـ interfacesوراثة class واحد فقط
الحالة (fields)مفيش instance fieldsفيه fields و constructors
التنفيذاختياري عبر default interface methods (C#‎ 8)أعضاء عادية + abstract
تغيير العقد لاحقاًإضافة member كان بيكسر المطبّقين، الـ default methods خففت دهإضافة non-abstract member آمن
الاستخدام النمطيالـ DI، الـ mocking في الاختبار، فصل الطبقاتTemplate Method، كود مشترك لعائلة أنواع
C#Payments.cs: interface + abstract base + concrete class
public record PaymentResult(bool Success, string? TransactionId);

public interface IPaymentGateway
{
    string Name { get; }
    Task<PaymentResult> ChargeAsync(decimal amount, string currency);

    // Default interface method: adds behaviour without breaking existing implementers
    string Describe() => $"Gateway: {Name}";
}

public abstract class GatewayBase : IPaymentGateway
{
    protected HttpClient Http { get; }
    protected GatewayBase(HttpClient http) => Http = http;

    public abstract string Name { get; }

    // Template Method: shared validation, the variable step is delegated
    public async Task<PaymentResult> ChargeAsync(decimal amount, string currency)
    {
        if (amount <= 0) return new PaymentResult(false, null);
        return await SendAsync(amount, currency);
    }

    protected abstract Task<PaymentResult> SendAsync(decimal amount, string currency);
}

public sealed class StripeGateway : GatewayBase
{
    public StripeGateway(HttpClient http) : base(http) { }
    public override string Name => "Stripe";

    protected override Task<PaymentResult> SendAsync(decimal amount, string currency)
        => Task.FromResult(new PaymentResult(true, Guid.NewGuid().ToString("N")));   // stub for the example
}

// Usage: callers depend on the INTERFACE only
IPaymentGateway gateway = new StripeGateway(new HttpClient());
Console.WriteLine(gateway.Describe());                 // Gateway: Stripe
PaymentResult r = await gateway.ChargeAsync(250m, "EGP");
Console.WriteLine(r.Success);                          // True
// new StripeGateway(...).Describe() would NOT compile: default members are reachable via the interface type

الشرح

  1. الكود اللي بيستخدم الـ gateway بيعرف IPaymentGateway بس، فتقدر تبدّل Stripe بـ PayPal أو fake في الاختبارات بدون ما تلمس المستهلك (ده أساس الـ Dependency Injection).
  2. GatewayBase بيدّي كود مشترك (التحقق من المبلغ) ويسيب خطوة الإرسال للمشتقات (Template Method). ده شيء الـ interface لوحده مش بيقدّمه.
  3. الـ default method Describe متاحة عن طريق متغير من نوع interface فقط، مش من متغير نوعه الـ class.
  4. Explicit implementation: لو class طبّق interfaceين فيهم نفس الاسم، تقدر تكتب string IReader.Read() => ... و string IWriter.Read() => ... وكل واحد بيتنادى من متغير نوعه الـ interface المقابل بس.
قاعدة القرار

ابدأ بـ interface لأي dependency أو عقد بين طبقات. استخدم abstract class لما يكون فيه كود مشترك وحالة حقيقية بين أنواع متقاربة جداً. ولو الـ abstract class ملوش حالة ولا كود، يبقى هو interface متنكّر.

09

مبادئ SOLID من زاوية C#‎

SOLID principles · how they map onto C# features
Basics

الـ SOLID ليها درس كامل بأمثلة و trade-offs في قسم المعمارية. هنا الربط بالمميزات اللي لسه اتعلمناها بس:

S: Single Responsibility

الـ class ليه سبب واحد للتغيير. مثال: BankAccount بيحمي الرصيد ومش بيبعت إيميلات ولا بيكتب لقاعدة بيانات.

O: Open/Closed

تضيف سلوك جديد بنوع جديد (override/implementation) من غير تعديل الكود الموجود. زي إضافة Triangle : Shape.

L: Liskov Substitution

أي Shape لازم يتحط مكان Shape ويشتغل صح. الـ override اللي بيرمي NotSupportedException علامة إنذار.

I: Interface Segregation

interfaces صغيرة ومركّزة بدل واحدة ضخمة، والـ class بيطبّق اللي محتاجه بس.

D: Dependency Inversion

الكود عالي المستوى بيعتمد على IPaymentGateway مش StripeGateway، والـ constructor injection بيوصّلهم.

10

الـ Nullable Reference Types

Nullable reference types · flow analysis · null-safety attributes
Deep dive

NullReferenceException هي أشهر exception في ‎.NET. الـ Nullable Reference Types (NRT) بتخلّي المترجم يتتبّع «ممكن يكون null ولا لأ» ويحذّرك قبل التشغيل. بتتفعّل في الـ csproj (وهي مفعّلة في القوالب الجديدة):

XMLMyApp.csproj
<PropertyGroup>
  <TargetFramework>net10.0</TargetFramework>
  <Nullable>enable</Nullable>                          <!-- reference types are non-null by default -->
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>   <!-- optional: make null warnings fail the build -->
</PropertyGroup>

القاعدة بعد التفعيل: string معناها «مش null أبداً»، و string? معناها «ممكن null». المترجم بيعمل flow analysis: بيتتبع حالة كل متغير (maybe-null أو not-null) بعد كل فحص.

C#Customers.cs
using System.Diagnostics.CodeAnalysis;

public class Customer
{
    public required string Name { get; init; }       // never null: required forces the caller to set it
    public string? MiddleName { get; init; }         // may legitimately be null
}

public static class CustomerLogic
{
    public static int MiddleLength(Customer c)
    {
        // return c.MiddleName.Length;               // warning CS8602: dereference of a possibly null reference
        return c.MiddleName?.Length ?? 0;            // null-conditional + null-coalescing
    }

    public static string Initials(Customer c)
    {
        if (c.MiddleName is { Length: > 0 } middle)  // flow analysis: 'middle' is non-null here
            return $"{c.Name[0]}{middle[0]}";
        return $"{c.Name[0]}";
    }

    // [NotNullWhen(true)] tells the compiler: if I return true, 'found' is NOT null
    public static bool TryFind(IEnumerable<Customer> all, string name, [NotNullWhen(true)] out Customer? found)
    {
        found = all.FirstOrDefault(c => c.Name == name);
        return found is not null;
    }
}

// ---- Program.cs (usage) ----
var list = new List<Customer> { new() { Name = "Mona" } };
if (CustomerLogic.TryFind(list, "Mona", out var cust))
    Console.WriteLine(cust.Name);                     // no warning: cust is known non-null inside the if

الشرح

  1. الـ c.MiddleName.Length المباشر بيطلّع تحذير لأن النوع string?. الحل بيتعمل بـ ?. (لو null رجّع null بدل ما يرمي) و ?? (قيمة بديلة).
  2. is { Length: > 0 } middle فحص null وطول في خطوة واحدة، وبعدها المترجم عارف إن middle مش null.
  3. الـ out Customer? بتاع TryFind ممكن يكون null، فالمترجم من غير attribute كان هيحذّرك عند استخدام cust.Name. الـ [NotNullWhen(true)] بيعلّمه إن القيمة سليمة لما الدالة ترجّع true. فيه attributes تانية: [MaybeNull], [NotNull], [MemberNotNull].
  4. في C#‎ 14 ينفع كمان تعيّن بشرط: customer?.Order = GetCurrentOrder(); والطرف اليمين مش بيتنفّذ لو customer null.
الـ NRT ضمان وقت compile مش وقت التشغيل

الـ runtime ما بيعرفش حاجة عن string?. بيانات جاية من JSON أو reflection أو ORM ممكن تكسر الوعد. وعامل الـ ! (null-forgiving) بيطفي التحذير بس من غير ما يتحقق: name!.Length هيرمي NRE لو null. استخدمه بحذر، وفضّل فحص أو required. وعلى حدود النظام (API inputs) لازم تتحقق فعلياً.

11

التعامل مع الـ Strings وتكلفة الـ Interpolation

String handling · StringBuilder · interpolation costs · comparison
Practical

الـ string في ‎.NET immutable وبيتخزّن كـ UTF-16. أي «تعديل» بينتج string جديد: بيحجز ذاكرة وينسخ الحروف.

C#Concatenation in loops, and comparison pitfalls
using System.Text;

// BAD: each += allocates a brand-new string and copies everything so far -> O(n^2) copying
string s = "";
for (int i = 0; i < 10_000; i++) s += i;

// GOOD: StringBuilder appends into a growable buffer -> O(n)
var sb = new StringBuilder(capacity: 64_000);        // pre-size when you roughly know the length
for (int i = 0; i < 10_000; i++) sb.Append(i);
string result = sb.ToString();

// Joining a sequence: let the library do it
string csv = string.Join(",", new[] { "a", "b", "c" });   // a,b,c

string role = "Admin";
// Comparison: ALWAYS state the comparison explicitly for non-UI text
bool isAdmin = string.Equals(role, "admin", StringComparison.OrdinalIgnoreCase);   // fast, culture-independent
// role.ToLower() == "admin"   -> allocates, and "I".ToLower() is "ı" under the Turkish culture

// Raw string literal (C# 11): no escaping for quotes or backslashes
string json = """
    { "name": "Mona", "path": "C:\temp" }
    """;

الشرح

  1. في الـ loop الأول: الـ string رقم k طوله ~k حرف، فمجموع النسخ ≈ n²/2 حرف و10,000 allocation. مع n كبير ده بيبطّئ ويضغط على الـ GC. الـ StringBuilder بيزوّد buffer داخلي بس لما يمتلئ.
  2. لكن a + b + c في سطر واحد مش مشكلة: المترجم بيحوّله لاستدعاء string.Concat واحد. المشكلة في الـ loops.
  3. الـ OrdinalIgnoreCase بيقارن بالـ code units بدون قواعد ثقافة معيّنة: أسرع وأأمن للمعرّفات والـ headers والأدوار. استخدم CurrentCulture فقط للنص اللي بيظهر للمستخدم.
  4. الـ raw string (""") ممتاز لـ JSON و SQL و regex لأنه بيتجاهل الـ escaping، وبيقص المسافات الزايدة بناءً على موضع الـ """ الختامي.

تكلفة الـ Interpolation

الـ $"..." مريح، ومن C#‎ 10 بيتترجم لـ DefaultInterpolatedStringHandler بيقلّل الـ allocations والـ boxing مقارنة بـ string.Format القديم. لكنه دايماً بيبني string كاملة فوراً. ده بيسبب مشكلة محددة في الـ logging:

C#Interpolation inside logging calls
// assume: ILogger logger; int orderId; string userId
// BAD: the string is built even when Information logging is disabled,
// and the output has no structured properties to search/filter by.
logger.LogInformation($"Order {orderId} placed by {userId}");

// GOOD: a constant message template; values become named properties,
// and formatting happens only if the level is enabled.
logger.LogInformation("Order {OrderId} placed by {UserId}", orderId, userId);

الـ analyzer CA2254 بيحذّرك من الغلط ده. (الـ logging نفسه هنشرحه في قسم الـ Observability.) ولو شغّال على نصوص كبيرة وعايز تتجنّب Substring اللي بتنسخ، استخدم ReadOnlySpan<char> (الجزء 2).

ملحوظتين سريعتين: الـ string interning معناه إن literals المتطابقة بتشاور على object واحد (ولهذا ReferenceEquals("a","a") بتكون true)، لكن ما تعتمدش عليها؛ استخدم == اللي بتقارن المحتوى. والـ char مش دايماً «حرف»: الإيموجي وبعض الحروف بتحتاج 2 chars (surrogate pair)، فـ "😀".Length == 2.

12

الـ init و required والـ Immutability

init, required, readonly and immutability
Practical

الـ object اللي مش بيتغيّر بعد ما اتبنى (immutable) أسهل في الفهم، وآمن في الـ multi-threading، ومش بيتعمله «تعديل غير متوقع» من كود تاني. C#‎ بتدّيك أدوات:

  • readonly للحقول: بتتعيّن في الـ constructor بس.
  • init accessor: property بتتعيّن في object initializer أو constructor بس، وبعدها قراءة فقط.
  • required (C#‎ 11): المترجم بيجبر المُنشئ يعيّن الـ member وقت الإنشاء.
  • with expression: نسخة معدّلة من object بدل تعديل الأصلي.
C#Product.cs
// ---- Product.cs ----
public class Product
{
    public required string Sku { get; init; }
    public required string Name { get; init; }
    public decimal Price { get; init; }
}
public readonly record struct Coords(double X, double Y);

// ---- Program.cs ----
var p = new Product { Sku = "A1", Name = "Pen", Price = 5m };    // OK
// p.Price = 6m;                          // error CS8852: init-only property cannot be assigned after construction
// var bad = new Product { Sku = "A1" };  // error CS9035: required member 'Name' must be set

// "Change" = create a modified copy (works with records and structs via 'with')
var origin = new Coords(0, 0);
var moved  = origin with { X = 3 };       // (3, 0); 'origin' is untouched

تحذير مهم: الـ immutability «سطحية» (shallow). لو الـ property نوعها List<string> فالـ reference ثابت لكن محتوى الـ list لسه ممكن يتغيّر. اعرضها كـ IReadOnlyList<T> أو استخدم ImmutableArray<T> من System.Collections.Immutable. ولو بتبني DTOs فـ required + init تركيبة ممتازة (هنشوفها في درس الـ DTOs).

13

الـ Records والـ Pattern Matching

Records · value equality · pattern matching · switch expressions
Deep dive

Records

الـ record نوع مخصص للبيانات اللي هويتها هي قيمتها. المترجم بيولّد لك: Equals/GetHashCode/== بمقارنة القيم، و ToString مقروء، و Deconstruct، ودعم with. (من توثيق Microsoft: الـ record class بيعتبر object متساويين لو نفس الـ runtime type ونفس قيم الأعضاء.)

C#Records.cs
// ---- Records.cs ----
public record Address(string City, string Street);
public record Customer(string Name, Address Address, int Age = 0);   // positional record
public readonly record struct Money(decimal Amount, string Currency);

// ---- Program.cs ----
var a1 = new Address("Cairo", "Tahrir");
var a2 = new Address("Cairo", "Tahrir");
Console.WriteLine(a1 == a2);                   // True   value equality
Console.WriteLine(ReferenceEquals(a1, a2));    // False  still two objects

var c1 = new Customer("Mona", a1, 30);
var c2 = c1 with { Age = 31 };                 // copy with one change
Console.WriteLine(c2);
// Customer { Name = Mona, Address = Address { City = Cairo, Street = Tahrir }, Age = 31 }

var (name, address, _) = c1;                   // Deconstruct (positional records only)
Console.WriteLine($"{name} lives in {address.City}");   // Mona lives in Cairo

الشرح

  1. record Customer(string Name, Address Address, int Age = 0) بيعرّف constructor و properties init-only (بنفس الأسماء) تلقائياً. ده فرق عن الـ primary constructor العادي اللي مش بيعمل properties.
  2. مقارنة a1 == a2 بتقارن الأعضاء واحد واحد. و Customer بيقارن Address بقيمته كمان (equality متداخلة).
  3. with بيعمل نسخة (shallow copy) ويعيّن الخاصية الجديدة. الأصل c1 يفضل Age=30.
  4. record struct = نفس الفكرة لكن value type (ومعاه readonly يخلّيه immutable).

إمتى؟ DTOs، value objects، رسائل/events، نتائج الدوال. إمتى لأ؟ entities لها هوية وحالة بتتغيّر (زي Order في الـ EF Core: بيتتبّع بالـ Id مش بالقيم). وانتبه: لو الـ record فيه عضو reference قابل للتغيير (مثل string[]) فالـ equality بتقارن المرجع، يعني ممكن تلاقي سجلّين «متساويين» وانت بتعدّل الـ array المشترك.

Pattern Matching

الـ patterns بتخليك تفحص شكل البيانات وتستخرج منها قيم في تعبير واحد. الأنواع: type، constant (بما فيها null)، relational (< >=)، logical (and or not)، property، positional، list.

C#Patterns.cs
public record DigitalOrder(string DownloadUrl);
public record PhysicalOrder(double WeightKg, string Country);

public static class Shipping
{
    public static decimal Cost(object? order) => order switch
    {
        null                                                => throw new ArgumentNullException(nameof(order)),
        DigitalOrder                                        => 0m,
        PhysicalOrder { WeightKg: <= 0 }                    => throw new ArgumentException("weight must be positive"),
        PhysicalOrder { WeightKg: <= 1.0, Country: "EG" }   => 30m,
        PhysicalOrder { WeightKg: <= 5.0, Country: "EG" }   => 50m,
        PhysicalOrder { Country: not "EG" } p when p.WeightKg > 20 => 400m,   // 'when' = extra condition
        PhysicalOrder p                                     => 100m + (decimal)p.WeightKg * 10m,
        _                                                   => throw new NotSupportedException(order.GetType().Name)
    };

    public static string Describe(int[] nums) => nums switch
    {
        []                    => "empty",
        [var only]            => $"one element: {only}",
        [1, .., 5]            => "starts with 1 and ends with 5",
        [_, _, ..]            => "two or more elements",
    };
}

// ---- Program.cs (usage) ----
Console.WriteLine(Shipping.Cost(new DigitalOrder("x")));              // 0
Console.WriteLine(Shipping.Cost(new PhysicalOrder(0.5, "EG")));       // 30
Console.WriteLine(Shipping.Cost(new PhysicalOrder(3, "EG")));         // 50
Console.WriteLine(Shipping.Cost(new PhysicalOrder(2, "DE")));         // 120
Console.WriteLine(Shipping.Describe([1, 2, 3, 4, 5]));                // starts with 1 and ends with 5
if (new object() is string { Length: > 0 } text) Console.WriteLine(text);   // 'is' pattern with property test

الشرح وتتبّع التنفيذ

  1. الـ switch expression بيجرّب الـ arms بالترتيب وبيرجّع أول واحد يطابق. PhysicalOrder(2,"DE"): يفشل مع null، DigitalOrder، {WeightKg: <= 0}، وفرع "EG" (الدولة DE)، وفرع not "EG" مع when p.WeightKg > 20 (الوزن 2)، فيوصل للـ arm العام: 100 + 2*10 = 120.
  2. ترتيب الـ arms مهم: لو وضعنا PhysicalOrder p قبل الأخص منها، المترجم هيرفض (الأخص unreachable). والـ arm الأخير _ يغطّي كل الأنواع الأخرى، وبدونه المترجم بيحذّر من عدم الاستيفاء (non-exhaustive).
  3. الـ list patterns: [] فاضي، [var only] عنصر واحد، .. slice لأي عدد. [1, .., 5] بيطابق المصفوفة الأولى بتاعتنا. الـ arms التلاتة [] و [var only] و [_, _, ..] بيغطّوا كل الأطوال.
14

الميزات الحديثة: Primary Constructors و Collection Expressions و C#‎ 14

Primary constructors · collection expressions · C# 13/14 highlights
Practical

Primary Constructors (C#‎ 12)

بتحط parameters الـ constructor مباشرة في header الـ class. المهم: دي parameters مش fields ولا properties (إلا في الـ records)، ومتاحة في كل أعضاء الـ class. المترجم بيخزّنها في حقل مخفي فقط لو استخدمتها داخل member. أشهر استخدام: الـ DI.

C#OrderService.cs
using Microsoft.Extensions.Logging;

public record Order(int Id);
public interface IOrderRepository { Task<Order?> FindAsync(int id); }

// Before C# 12: private readonly fields + an explicit constructor that assigns them.
// Now: parameters captured directly.
public class OrderService(IOrderRepository repo, ILogger<OrderService> logger)
{
    public async Task<Order?> GetAsync(int id)
    {
        logger.LogInformation("Loading order {OrderId}", id);
        return await repo.FindAsync(id);
    }
}
  • الـ parameters قابلة للتعديل (repo = null مسموح)، وده ممكن يبقى مصدر bug. لو عايزها ثابتة فحطها في private readonly field بنفسك.
  • لو مرّرت الـ parameter للـ base class واستخدمته كمان في المشتق، المترجم بيحذّر لأنك بتعمل نسخة تانية من القيمة. استخدم property الـ base.
  • أي constructor إضافي لازم ينادي الـ primary بـ : this(...).

Collection Expressions (C#‎ 12)

C#CollectionExpressions.cs
int[] a = [1, 2, 3];
List<int> b = [4, 5];
int[] all = [.. a, .. b, 6];            // spread: [1, 2, 3, 4, 5, 6]
IEnumerable<string> none = [];          // an empty collection of the target type
Span<int> span = [10, 20, 30];          // target-typed: the compiler picks the best creation strategy

Console.WriteLine(string.Join(",", all));   // 1,2,3,4,5,6

نفس الصيغة [ ] بتشتغل مع arrays و List<T> و Span<T> والـ interfaces الشائعة والأنواع اللي فيها [CollectionBuilder]. النوع بيتحدد من السياق (target-typed). الـ .. بينسخ عناصر أي sequence جوه. ملحوظة: مع IEnumerable<T> النتيجة collection جاهزة مش lazy.

مميزات C#‎ 14 (مع ‎.NET 10)

C#CSharp14.cs
public class Person
{
    // 'field' keyword: the compiler generates the backing field; you reference it as 'field'
    public string Name
    {
        get;
        set => field = value?.Trim() ?? throw new ArgumentNullException(nameof(value));
    } = "";
}

public static class StringExtensions
{
    // Extension members: an 'extension' block can declare extension PROPERTIES, not just methods
    extension(string text)
    {
        public bool IsBlank => string.IsNullOrWhiteSpace(text);
        public string Truncate(int max) => text.Length <= max ? text : text[..max];
    }
}

// ---- Program.cs (usage) ----
var person = new Person { Name = "  Mona  " };
Console.WriteLine($"[{person.Name}]");        // [Mona]
Console.WriteLine("   ".IsBlank);             // True
Console.WriteLine("abcdef".Truncate(3));      // abc
Person? maybe = null;
maybe?.Name = "x";                            // null-conditional assignment: skipped because maybe is null

الشرح

  1. field: بدل ما تعمل حقل _name منفصل عشان تضيف تحقق أو تنضيف في الـ setter، المترجم بيولّد الحقل وانت بتوصله بالكلمة field. لو عندك عضو اسمه field فعلاً استخدم @field.
  2. Extension members: الـ extension(string text) block بيعرّف المستقبِل مرة واحدة، وتحته properties و methods. الـ " ".IsBlank بيتكتب كأنها property عادية. الصيغة القديمة this string text لسه شغالة.
  3. Null-conditional assignment: maybe?.Name = "x" معناها: لو maybe مش null اعمل التعيين، وإلا تجاهل الطرف اليمين كله (من غير ما يتقيّم).
  4. كلمة تحذير: دي ميزات C#‎ 14، بتحتاج SDK بتاع ‎.NET 10 و LangVersion مناسب. الإصدارات الأقدم هتديك أخطاء compile.

فيه كمان في C#‎ 14: implicit conversions بين Span<T> و ReadOnlySpan<T> والمصفوفات، nameof(List<>) لأنواع generic غير مغلقة، parameters في الـ lambda بـ modifiers من غير ما تكتب النوع ((text, out result) => ...)، وتحميل compound assignment operators (+=) بشكل مخصص.

15

الـ Operator Overloading والـ Conversions

Operator overloading · implicit and explicit conversions
Practical

بتخليك تكتب a + b أو a < b لنوعك الخاص. استخدمها فقط للأنواع «القيمية» (value-like) اللي المعنى الرياضي بتاعها واضح (Money، Vector، Duration)، مش لحاجات بتتفاجئ بيها.

C#Money.cs
public readonly struct Money : IEquatable<Money>, IComparable<Money>
{
    public decimal Amount { get; }
    public string Currency { get; }

    public Money(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }

    // Arithmetic: only meaningful between the same currency
    public static Money operator +(Money a, Money b) { EnsureSame(a, b); return new(a.Amount + b.Amount, a.Currency); }
    public static Money operator -(Money a, Money b) { EnsureSame(a, b); return new(a.Amount - b.Amount, a.Currency); }
    public static Money operator *(Money a, decimal factor) => new(a.Amount * factor, a.Currency);

    // Equality operators MUST come with Equals + GetHashCode, and relational ones come in pairs
    public static bool operator ==(Money a, Money b) => a.Equals(b);
    public static bool operator !=(Money a, Money b) => !a.Equals(b);
    public static bool operator <(Money a, Money b)  => a.CompareTo(b) < 0;
    public static bool operator >(Money a, Money b)  => a.CompareTo(b) > 0;
    public static bool operator <=(Money a, Money b) => a.CompareTo(b) <= 0;
    public static bool operator >=(Money a, Money b) => a.CompareTo(b) >= 0;

    // Conversion: explicit because it throws away the currency (information loss)
    public static explicit operator decimal(Money m) => m.Amount;

    public bool Equals(Money other) => Amount == other.Amount && Currency == other.Currency;
    public override bool Equals(object? obj) => obj is Money m && Equals(m);
    public override int GetHashCode() => HashCode.Combine(Amount, Currency);
    public int CompareTo(Money other) { EnsureSame(this, other); return Amount.CompareTo(other.Amount); }
    public override string ToString() => $"{Amount:N2} {Currency}";

    private static void EnsureSame(Money a, Money b)
    {
        if (a.Currency != b.Currency)
            throw new InvalidOperationException($"Currency mismatch: {a.Currency} vs {b.Currency}");
    }
}

// ---- Program.cs (usage) ----
var price = new Money(100m, "EGP");
var tax   = new Money(14m, "EGP");
Console.WriteLine(price + tax);        // 114.00 EGP
Console.WriteLine(price > tax);        // True
decimal raw = (decimal)price;          // explicit cast required: 100
// price + new Money(5m, "USD");       // throws InvalidOperationException (currency mismatch)

الشرح

  1. الـ operators دوال static بكلمة operator. price + tax بيتترجم لاستدعاء Money.op_Addition(price, tax).
  2. لو عرّفت == لازم تعرّف !=، ولازم تـ override الـ Equals(object) و GetHashCode بشكل متسق، وإلا الـ Dictionary والـ HashSet هيتصرّفوا غلط (هنشرحه بالتفصيل في «Equality and GetHashCode» في الجزء 2). وكذلك < > و <= >= بيتعرّفوا أزواج.
  3. implicit مقابل explicit: implicit لتحويل مضمون وآمن بدون فقد معلومات (int → long). explicit لو ممكن يفقد معلومات أو يرمي exception، فبيتطلب cast صريح عشان القارئ يشوف الخطورة.
  4. لو مش محتاج التحكم اليدوي: public readonly record struct Money(decimal Amount, string Currency) بيدّيك equality و ToString مجاناً، وبتضيف بس الـ operators اللي محتاجها.
16

أخطاء شائعة وتشخيص

Common mistakes and troubleshooting
Pitfalls
الغلطةالمشكلةالإصلاح
Mutable struct بيتعدّل جوه List<T> أو foreachlist[0].X = 5 بيعدّل نسخة مؤقتة (المترجم بيمنعها)، و foreach variable نسخةخلّي الـ struct readonly، أو استخدم class، أو استبدل العنصر بنسخة جديدة
Boxing في hot path (تمرير struct كـ object/interface)allocation لكل نداء وضغط على الـ GCgenerics، أو IEquatable<T>، وراجع بـ profiler/BenchmarkDotNet
استخدام new بدل overrideنتيجة مختلفة حسب نوع المتغير، الـ polymorphism بيكسرvirtual في الأساس و override في المشتق
نداء virtual method من constructorالمشتق بيتنفّذ قبل ما حقوله تتهيّأاقفل الـ class (sealed) أو أجّل التهيئة لـ method منفصلة
إسكات تحذيرات null بـ ! في كل حتةNRE وقت التشغيل زي زمان بالظبطفحص صريح، required، أو تصميم ميسمحش بالـ null
s += x في loop كبيرO(n²) نسخ وأحمال GCStringBuilder أو string.Join
Interpolation داخل logger.Log*بيبني string دايماً ويفقد الـ structured propertiesmessage template + parameters
Record فيه عضو مصفوفة/List قابل للتغييرالمقارنة بالمرجع، فالـ equality مش زي المتوقعاستخدم ImmutableArray أو قارن المحتوى يدوياً
Primary constructor parameter متغيّرالقيمة بتتغيّر في النص بدون ما تلاحظانسخها لـ readonly field لو عايزها ثابتة
تعريف == بدون Equals/GetHashCodeالـ HashSet/Dictionary بيدوّروا غلططبّق الـ 4 متسقين، أو استخدم record struct
إزاي تكتشف المشكلة وقت التصحيح

أي سلوك «غريب» في النسخ ⇐ اسأل: ده value type ولا reference type؟ في الـ debugger شوف لو المتغيرين بيشاوروا على نفس الـ object (Make Object ID في Visual Studio). وفي الأداء: قيس قبل ما تحسّن (BenchmarkDotNet أو dotnet-counters) وراقب الـ allocations.

17

Knowledge Check

Takeaways · conceptual questions · code reading · interview questions
Basics

أهم النقاط

  • C#‎ ⇐ IL ⇐ JIT. النوع الثابت بيتفحص وقت الـ compile، و var مش dynamic.
  • decimal للفلوس، و double مش دقيق للكسور العشرية، والـ integer overflow صامت إلا لو checked.
  • Value type: المتغير يحتوي القيمة والتعيين ينسخها. Reference type: المتغير يحتوي مرجع والتعيين ينسخ المرجع. كل حاجة تتمرّر by value، و ref بيمرّر المتغير.
  • Boxing = allocation + نسخ. أي struct في object/interface بيتعمله box.
  • virtual/override = polymorphism حقيقي حسب النوع الفعلي؛ new بيخبّي بس. الأساس بيتبني قبل المشتق.
  • Interface للعقد والـ DI، abstract class لكود وحالة مشتركة. تفضّل Composition على Inheritance.
  • NRT ضمان compile-time؛ ! بيسكت التحذير مش بيحل المشكلة.
  • Records للبيانات ذات الـ value equality؛ pattern matching لفحص الشكل بالترتيب.
  • الـ Strings immutable: StringBuilder في الـ loops، ومقارنات Ordinal، و message templates في الـ logging.

أسئلة مفاهيمية

C#‎ بتمرر الـ objects by reference؟

لأ. بتمرّر كل حاجة by value. في الـ reference types القيمة اللي بتتنسخ هي المرجع. عشان كده تعديل حالة الـ object بيظهر عند المُنادي لكن تعيين المتغير لـ object جديد مش بيظهر (إلا لو ref).

ليه 0.1 + 0.2 != 0.3 في double، ومع decimal بيشتغل؟

الـ double بيمثّل الأرقام في base-2، والـ 0.1 كسر دوّار فيه، فبيتقرّب. الـ decimal بيمثّل في base-10 فالأرقام العشرية بتتمثّل بدقة. مقابل ده decimal أبطأ وأكبر.

إيه الفرق بين override و new؟

override بيستبدل خانة الـ virtual فالنسخة بتتحدد بالنوع الفعلي. new بيعرّف method جديدة بنفس الاسم بتتحدد بالنوع الثابت للمتغير، فبيكسر الـ polymorphism.

متى تختار interface بدل abstract class؟

لما تكون محتاج عقد بدون حالة أو كود، أو class يطبّق عدة عقود، أو تحتاج mocking/DI. الـ abstract class لما يبقى فيه كود وحالة مشتركة فعلاً.

ليه الـ Nullable Reference Types مش بتمنع NullReferenceException تماماً؟

لأنها تحليل وقت compile، والـ runtime مبيعرفش عنها. البيانات الخارجية (JSON، ORM، reflection) والـ ! ممكن يدخّلوا null.

قراءة كود

إيه ناتج: object o = 7; o = (int)o + 1; long x = (long)o; ؟

o بيحتوي int (8 بعد الجمع ثم boxing جديد). الـ cast (long)o بيرمي InvalidCastException لأن الـ unboxing لازم يطابق النوع بالظبط (int)، ولازم تعمل (long)(int)o.

record P(string[] Tags); var a = new P(arr); var b = new P(arr); arr[0] = "x"; إيه ناتج a == b ؟

true. الـ equality بتقارن Tags بالمرجع (Equals العادية للـ array) وهي نفس المصفوفة قبل وبعد التعديل. المقارنة مبتتأثرش بمحتواها.

أسئلة إنترفيو شائعة

اشرح الفرق بين struct و class ومتى تستخدم كل واحد؟

struct value type بيتنسخ عند التعيين، مناسب لقيم صغيرة immutable (أقل من حوالي 16 byte) ومش بيتعمله boxing كتير. class reference type مناسب للكيانات والأحجام الكبيرة وأي حاجة ليها هوية أو حالة بتتغيّر.

إيه بيحصل في الذاكرة لما تعمل boxing؟ وإزاي تتجنبه؟

بيتحجز object على الـ heap فيه نسخة من القيمة (مع header)، والمتغير بيشاور عليه. بنتجنبه بالـ generics (List<int>)، وتطبيق IEquatable<T>، وتجنّب تمرير struct كـ object.

ليه نستخدم records بدل classes للـ DTOs؟ وإمتى لأ؟

الـ value equality والـ with و ToString/Deconstruct مجاناً وبشكل immutable تلقائي. لا للـ entities اللي ليها هوية وحالة بتتغيّر وبيتتبّعها EF بالـ Id.

↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

مصادر تعليمية ومتقدمة — Third-party & advanced reading

خريطة التغطية: 12 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapC# Fundamentals and Type System§04
RoadmapValue Types vs Reference Types§05
RoadmapClasses and Objects§06
RoadmapEncapsulation, Inheritance, Polymorphism, and Abstraction§07
RoadmapInterfaces vs Abstract Classes§08
RoadmapSOLID Principles§09
RoadmapNullable Reference Types§10
RoadmapRecords and Pattern Matching§13
SuggestedString handling, StringBuilder, interpolation costs§11
Suggestedinit, required, and immutability§12
SuggestedPrimary constructors and collection expressions (modern C#)§14
SuggestedOperator overloading and conversions§15

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس