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

C# الجزء 2: Generics والـ Collections والـ LINQ والذاكرة

C# — Part 2: Generics, Collections, Delegates, LINQ and Memory

الجزء اللي بيحوّلك من «بعرف الـ syntax» لـ «بفهم إيه اللي بيحصل تحت»: Generics وconstraints وvariance، الـ Collections وإزاي Dictionary بيشتغل من جوه، Equality وGetHashCode، الـ Exceptions، Delegates وEvents، Lambdas وClosures، LINQ والـ deferred execution، Extension Methods، IDisposable، الـ Garbage Collector، وSpan/Memory.

  • Intermediate
  • ~34 min read
  • 14 sections
  • 32 code examples
  • 4 diagrams
  • 11 questions
  • Priority L1 · Essential
  • .NET 10 LTS · C# 14

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

مفيش متطلبات C# سابقة: Part 1 بيبدأ من الصفر (أول برنامج، متغيرات، شروط، loops، collections، methods، أول class) وبعدين بينزل للتفاصيل الداخلية.

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

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

01

الـ Generics والـ Constraints والـ Variance

Generics · type parameters · constraints · covariance and contravariance
Deep dive

قبل الـ generics (قبل C#‎ 2) لو عايز collection تشيل أي نوع كنت بتستخدم ArrayList اللي بتخزن object. النتيجة: boxing للـ value types، و casts في كل قراءة، وأخطاء النوع بتطلع وقت التشغيل مش وقت الـ compile. الـ generics حلّت ده بإنك تكتب الكود مرة واحدة وانت سايب النوع كـ parameter.

C#Before and after generics
using System.Collections;          // ArrayList (legacy, avoid)
using System.Collections.Generic;  // List<T>

// Non-generic: stores object. Every int is boxed; every read needs a cast.
ArrayList old = new();
old.Add(10);
old.Add("oops");                   // compiles! the mistake is hidden
int first = (int)old[0]!;          // unbox
int second = (int)old[1]!;         // InvalidCastException at RUNTIME

// Generic: the compiler enforces the type, no boxing, no cast.
List<int> modern = new();
modern.Add(10);
// modern.Add("oops");             // compile-time error CS1503
int x = modern[0];                 // direct read from int[]

شرح الكود

  1. الـ ArrayList بتاخد object فالـ 10 بيتعمله boxing (allocation على الـ heap، شفنا ده في Part 1). والقراءة (int)old[0] بتعمل unboxing.
  2. السطر التاني بيدخل string في collection المفروض فيها أرقام: الـ compiler مبيعترضش، والانفجار بيحصل بعدين في الـ production.
  3. الـ List<int> جواها int[] مباشرة: مفيش boxing ومفيش cast، والخطأ بيتمنع وقت الـ compile.

إزاي الـ CLR بينفّذ الـ Generics؟ (Reified Generics)

في C#‎ الـ generics reified: معلومة النوع T بتفضل موجودة وقت التشغيل (عكس Java اللي بتمسحها: type erasure). فينفع تعمل typeof(T) و new T[] وتسأل x is T. والـ JIT بيشتغل كده:

Value type كـ T (مثلاً List<int>)

الـ JIT بيولّد native code مخصوص لكل value type مختلف. فـ List<int> و List<double> ليهم كود machine منفصل، فيه أحجام ثابتة وعمليات مباشرة من غير boxing. ده السبب إن الـ generics سريعة.

Reference type كـ T (مثلاً List<string>)

كل الـ references بنفس الحجم (pointer) فالـ JIT بيعمل كود واحد مشترك لكلهم (canonical form) مع metadata بتفرّق النوع وقت الحاجة. ده بيوفر ذاكرة code ووقت JIT.

النتيجة العملية

الـ generic type مع value type آمن أداءً (من غير boxing). ومع reference types الأداء ممتاز كمان. بس لو عملت instantiate لنفس الـ generic مع عشرات الـ structs المختلفة فكل واحد بيتجمّع (JIT) لوحده، ودي تكلفة startup تلاحظها في التطبيقات الكبيرة جداً (وبيتعالج بـ ReadyToRun/NativeAOT).

Generic Constraints

الـ T بدون قيود هو object فعلياً: متقدرش تستدعي عليه حاجة. الـ constraints بتقول للـ compiler «T لازم يحقق كذا» فيسمحلك تستخدم الأعضاء دي.

Constraintالمعنىبيسمح بإيه
where T : class / class?reference type (غير nullable / nullable)مقارنة بـ null، as
where T : structnon-nullable value typeT? = Nullable<T>، ومنع boxing
where T : notnullأي نوع non-nullableتحذيرات الـ nullable analysis
where T : new()لازم parameterless constructor publicnew T()
where T : BaseClassيرث من class معينأعضاء الـ BaseClass
where T : IComparable<T>يطبّق interfaceاستدعاء أعضاء الـ interface
where T : unmanagedstruct من غير أي references جواهsizeof, stackalloc, pointers
where T : allows ref struct (C#‎ 13)يسمح بـ Span<T> كـ type argumentgenerics مع ref structs
C#Constraints.cs — generic methods, constraints and generic math
using System.Numerics;

public interface IEntity { int Id { get; } }

public static class Generic
{
    // 1) Constraint = base contract. Without "where T : IEntity", t.Id would not compile.
    public static T? FindById<T>(IEnumerable<T> items, int id) where T : IEntity
    {
        foreach (var item in items)
            if (item.Id == id) return item;
        return default;                      // null for classes, zero-value for structs
    }

    // 2) new() lets the method create instances.
    public static T Create<T>() where T : class, new() => new T();

    // 3) Generic math (C# 11+): static abstract members in interfaces.
    public static T Sum<T>(IEnumerable<T> values) where T : INumber<T>
    {
        T total = T.Zero;                    // static abstract member
        foreach (var v in values) total += v; // operator + via interface
        return total;
    }

    // 4) Compare any two comparable values.
    public static T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) >= 0 ? a : b;
}

// Usage
Console.WriteLine(Generic.Sum(new[] { 1, 2, 3 }));          // 6      (T = int)
Console.WriteLine(Generic.Sum(new[] { 1.5, 2.5 }));         // 4      (T = double)
Console.WriteLine(Generic.Max("apple", "banana"));          // banana

شرح الكود + الـ Trace

  1. FindById: من غير where T : IEntity السطر item.Id مش هيتعمله compile لأن T مجهول. والـ default بيرجّع null للـ classes وصفر للـ structs ولذلك الـ return type T?.
  2. Create: الـ new() constraint هو الوحيد اللي بيسمح بـ new T(). (تحت الغطا بيستخدم Activator.CreateInstance فهو أبطأ من new العادية.)
  3. Sum: الـ generic math بتسمح بـ T.Zero و += لأن INumber<T> بيعرّف static abstract members. نفس الدالة بتشتغل على int و double و decimal من غير boxing.
Sum(new[]{1,2,3}): الـ compiler بيستنتج T = int من الـ argument (type inference).
الـ JIT بيولّد نسخة Sum<int> مخصوصة (لأن int value type)، و T.Zero بتتحول لـ 0 ثابت.
الـ loop بتجمّع: total = 1 ثم 3 ثم 6 بعمليات int مباشرة.
النتيجة 6 بتتطبع.

Covariance و Contravariance (الـ Variance)

السؤال: لو Dog يرث Animal، هل IEnumerable<Dog> ينفع يتعامل كـ IEnumerable<Animal>؟ الإجابة: أيوه بس في الـ interfaces والـ delegates اللي بتعلن ده بكلمة out أو in.

  • Covariant (out T): النوع بيطلّع T بس (مصدر). عشان كده IEnumerable<out T> و Func<out TResult>.
  • Contravariant (in T): النوع بياخد T بس (مستهلك). عشان كده IComparer<in T> و Action<in T>.
  • Invariant (الافتراضي): List<T> بتقرأ وتكتب فمفيش variance، وإلا هتقدر تضيف Cat في list كلاب.
C#Variance.cs
public class Animal { public string Name = "animal"; }
public class Dog : Animal { }

IEnumerable<Dog> dogs = new List<Dog> { new(), new() };
IEnumerable<Animal> animals = dogs;            // OK: covariance (read-only producer)

Action<Animal> feed = a => Console.WriteLine($"feeding {a.Name}");
Action<Dog> feedDog = feed;                    // OK: contravariance (an Animal-consumer can consume Dogs)

List<Dog> list = new();
// List<Animal> bad = list;                    // compile error: List<T> is invariant

// Arrays are covariant by (a regrettable) legacy decision:
Animal[] arr = new Dog[2];
arr[0] = new Animal();                         // compiles, throws ArrayTypeMismatchException at runtime

شرح

  1. السطر التاني آمن لأن IEnumerable<out T> مفيهوش غير قراءة: مفيش طريقة تدخل Cat جواه.
  2. الـ Action<Animal> تقدر تستخدمها مكان Action<Dog> لأن أي حاجة بتتعامل مع Animal بتتعامل مع Dog (الاتجاه معكوس = contra).
  3. الـ variance بتشتغل بس مع reference types كـ type arguments؛ IEnumerable<int> مش بيتحول لـ IEnumerable<object> لأنه محتاج boxing.
  4. الـ arrays covariant لأسباب تاريخية، وده اللي بيخلي آخر سطر يترمي عليه exception وقت التشغيل. استخدم IReadOnlyList<T> بدلها لما تحتاج variance آمن.
02

الـ Collections والـ Collection Interfaces

Collections · List, Dictionary, HashSet, Queue · internals and interfaces
Deep dive

اختيار الـ collection الغلط هو من أكتر أسباب البطء في كود الـ backend: List.Contains جوه loop بتحوّل O(n) لـ O(n²)، و dictionary بـ key فيه hash سيئ بتحوّل الـ O(1) لـ O(n). عشان تختار صح لازم تفهم هي بتخزن إزاي.

List<T> من جوه: Array بتكبر

C#ListGrowth.cs
var list = new List<int>();
Console.WriteLine($"Count={list.Count} Capacity={list.Capacity}");   // 0, 0

int lastCap = list.Capacity;
for (int i = 0; i < 20; i++)
{
    list.Add(i);
    if (list.Capacity != lastCap)
    {
        Console.WriteLine($"Add #{i + 1}: capacity {lastCap} -> {list.Capacity}");
        lastCap = list.Capacity;
    }
}
// Output:
// Add #1: capacity 0 -> 4
// Add #5: capacity 4 -> 8
// Add #9: capacity 8 -> 16
// Add #17: capacity 16 -> 32

var presized = new List<int>(capacity: 10_000);  // one allocation, no re-copies

شرح

  1. الـ List<T> بتحتفظ بـ array داخلية T[] وعدّاد Count. الـ Capacity هو حجم الـ array.
  2. أول Add بيعمل array حجمها 4. لما تمتلي، بتتعمل array بالضعف وبيتنسخ فيها كل العناصر ثم بتتلغى القديمة.
  3. عشان كده Add هو O(1) amortized: غالباً O(1) وأحياناً O(n) بس نادر. بينما Insert في الأول و Remove و Contains كلهم O(n).
  4. لو تعرف الحجم تقريباً مسبقاً مرر capacity وتفادى النسخ والضغط على الـ GC.

Dictionary<TKey,TValue> من جوه

الـ dictionary عبارة عن hash table بـ chaining مبني على arrays: array للـ buckets و array للـ entries. الـ lookup بيمشي كده:

dict["bob"] key.GetHashCode()h = 0x5A91... bucket indexh mod buckets.Length = 2 buckets[ ] [0] empty [1] → entry 0 [2] → entry 1 entries[ ] 0: ann · hash · next=-1 1: eve · hash · next=3 3: bob · hash · next=-1 1) bucket → first entry (eve) 2) hash equal? Equals(key)? no 3) follow next → bob ✓ found
Lookup في Dictionary: نحسب الـ hash، نطلع الـ bucket، ونمشي على سلسلة الـ entries مقارنين بـ Equals لحد ما نلاقي المفتاح
  • الـ GetHashCode بيحوّل المفتاح لرقم، والـ bucket = الرقم mod حجم الـ array (حجم بيكون عدد أولي). كل bucket بيشاور على أول entry، وكل entry فيه next للـ entry اللي بعده في نفس الـ bucket (collision).
  • لو المفاتيح hash-ها كويس (موزّع) فالسلاسل قصيرة جداً والـ lookup O(1) متوسط. لو الـ GetHashCode بيرجّع نفس الرقم لكل حاجة، كل المفاتيح تتكوّم في bucket واحد والـ lookup بقى O(n).
  • لما الـ entries تخلص، الـ dictionary بتكبّر (resize) وبتعيد توزيع كل المفاتيح: عملية تقيلة، فمرر capacity لو تعرف الحجم.
C#DictionaryUsage.cs
var stock = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
    ["apple"] = 10,
    ["pear"] = 4,
};

// Safe reads: ONE hash lookup, no exception.
if (stock.TryGetValue("APPLE", out int qty))      // case-insensitive thanks to the comparer
    Console.WriteLine($"apple: {qty}");            // apple: 10

int pears = stock.GetValueOrDefault("pear");       // 4
int plums = stock.GetValueOrDefault("plum", -1);   // -1 (missing)

stock.TryAdd("kiwi", 7);                           // false if the key already exists (no throw)
// stock.Add("kiwi", 8);                           // would throw ArgumentException (duplicate key)
// int bad = stock["mango"];                       // would throw KeyNotFoundException

// Anti-pattern: two lookups
if (stock.ContainsKey("pear")) { var v = stock["pear"]; }   // hashes twice - use TryGetValue

foreach (var (name, count) in stock)               // deconstruction of KeyValuePair
    Console.WriteLine($"{name} = {count}");

شرح

  1. الـ StringComparer.OrdinalIgnoreCase بيغيّر تعريف المساواة والـ hash مع بعض فـ "APPLE" بتلاقي "apple". من غيره المقارنة case-sensitive.
  2. الـ indexer القراءة بيرمي KeyNotFoundException، فاستخدم TryGetValue لما الـ key ممكن يكون غايب.
  3. ContainsKey ثم indexer = حسابين للـ hash. TryGetValue = حساب واحد.

باقي الـ Collections: إمتى تستخدم إيه

النوعالتخزين الداخليالعمليات الأساسيةاستخدمه لما
List<T>array بتكبرindex O(1) · Add O(1)* · Contains/Remove O(n)الافتراضي لأي sequence
Dictionary<K,V>hash tableget/set/remove O(1) avglookup بالـ key
HashSet<T>hash table (keys بس)Add/Contains O(1) avg · عمليات المجموعاتuniqueness و membership
Queue<T>circular arrayEnqueue/Dequeue O(1)FIFO (jobs, BFS)
Stack<T>arrayPush/Pop O(1)LIFO (undo, DFS)
PriorityQueue<E,P>array-backed min-heapEnqueue/Dequeue O(log n)scheduling، أقصر مسار
LinkedList<T>doubly linked nodesinsert/remove عند node معروفة O(1)نادراً جداً (cache-unfriendly)
SortedDictionary<K,V> / SortedSet<T>red-black treeO(log n) + ترتيبمحتاج iteration مرتب
FrozenDictionary / FrozenSet (‎.NET 8)مُحسّنة للقراءة بعد البناءlookup أسرع، بناء أبطأlookup tables ثابتة بعد الـ startup
ConcurrentDictionary / ImmutableArraythread-safe / immutable—مشاركة بين threads / snapshots

الـ data structures نفسها (الـ trees والـ heaps والـ hash tables) متشرحة بالتفصيل في درس Data Structures، هنا بنركز على استخدامها في ‎.NET.

الـ Collection Interfaces: صمّم الـ API بيها

C#Interfaces in signatures
// Hierarchy (simplified):
// IEnumerable<T>            -> can be foreach'ed (read forward only)
//  └ IReadOnlyCollection<T> -> + Count
//     └ IReadOnlyList<T>    -> + indexer [i]
//  └ ICollection<T>         -> + Count, Add, Remove, Contains, Clear (mutable)
//     └ IList<T>            -> + indexer, Insert, RemoveAt
// IReadOnlyDictionary<K,V> / IDictionary<K,V>, ISet<T> / IReadOnlySet<T>

public class OrderService
{
    private readonly List<Order> _orders = new();

    // ACCEPT the most general type you need...
    public decimal Total(IEnumerable<Order> orders) => orders.Sum(o => o.Amount);

    // ...RETURN a read-only view so callers can't mutate your internal state.
    public IReadOnlyList<Order> Orders => _orders;

    // Cheaper than copying: expose without allocation, still immutable to the caller.
}

public record Order(int Id, decimal Amount);

// Mutation during enumeration is detected:
var items = new List<int> { 1, 2, 3 };
foreach (var i in items)
    if (i == 2) items.Remove(i);   // InvalidOperationException: Collection was modified

شرح

  1. Accept general، return specific-but-safe: المعاملات بنيجي بأقل interface مطلوب (IEnumerable<T>) عشان نقبل أي مصدر. والـ return بيكون IReadOnlyList<T> عشان نحمي الـ state الداخلي.
  2. تنبيه: IReadOnlyList مجرد view على نفس الـ list؛ لو المستدعي عمل cast لـ List<Order> هيقدر يعدّل. لو الحماية الصارمة مطلوبة استخدم ImmutableArray أو AsReadOnly().
  3. الـ List<T> جواها رقم _version بيزيد مع كل تعديل، والـ enumerator بيقارن بيه في كل MoveNext. ده سبب الـ exception في آخر مثال. الحل: iterate على نسخة، أو استخدم RemoveAll(predicate).
03

الـ Equality والـ GetHashCode

Equality · Equals, ==, IEquatable, GetHashCode contract · comparers
Deep dive

في C#‎ فيه أكتر من معنى لـ «متساويين». لو مفهمتش الفروق دي هتدخل في bugs غريبة: عناصر مش بتتلاقي في HashSet، أو key اختفى من Dictionary بعد ما عدّلت property فيه.

ReferenceEquals(a, b)

هل الاتنين بيشاوروا على نفس الـ object؟ مفيش override.

a.Equals(b)

المساواة المنطقية. الافتراضي في الـ class = reference equality، وفي الـ struct = مقارنة الحقول. تقدر تعمله override.

a == b

الـ operator. للـ reference types الافتراضي = reference equality (إلا لو معمول overload زي string). للـ records بيقارن بالقيمة.

IEquatable<T>

نسخة strongly-typed من Equals من غير boxing. الـ collections العامة بتستخدمها لو موجودة.

العقد (The Contract)

القاعدة الذهبية

لو a.Equals(b) يرجّع true لازم a.GetHashCode() == b.GetHashCode(). العكس مش لازم (collision مسموح). ولازم الـ hash ميتغيرش طول ما الـ object جوه hash-based collection. لو عملت override لواحد منهم لازم تعمل للتاني.

C#Money.cs — correct Equals / GetHashCode
public sealed class Money : IEquatable<Money>
{
    public decimal Amount { get; }
    public string Currency { get; }

    public Money(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency ?? throw new ArgumentNullException(nameof(currency));
    }

    // Strongly-typed equality: the one that does the real work.
    public bool Equals(Money? other) =>
        other is not null &&
        Amount == other.Amount &&
        string.Equals(Currency, other.Currency, StringComparison.Ordinal);

    // Object-level override delegates to the typed one.
    public override bool Equals(object? obj) => Equals(obj as Money);

    // Hash MUST use exactly the fields that Equals compares.
    public override int GetHashCode() => HashCode.Combine(Amount, Currency);

    public static bool operator ==(Money? a, Money? b) => a is null ? b is null : a.Equals(b);
    public static bool operator !=(Money? a, Money? b) => !(a == b);
}

// Usage
var a = new Money(10m, "USD");
var b = new Money(10m, "USD");
Console.WriteLine(a == b);                         // True  (value equality)
Console.WriteLine(ReferenceEquals(a, b));          // False (two objects)

var set = new HashSet<Money> { a };
Console.WriteLine(set.Contains(b));                // True  (same hash + Equals)

شرح وتتبع

  1. الـ Equals(Money?) بيقارن نفس الحقول اللي بنحسب منها الـ hash: Amount و Currency.
  2. HashCode.Combine بيدمج الـ hashes بشكل موزّع كويس ومتطوّر لكل process (مش ثابت بين التشغيلات، فمتخزنهوش في ملف أو database).
  3. الـ == بيتأكد من null الأول قبل ما يستدعي Equals عشان ميحصلش NullReferenceException.
set.Contains(b): الـ HashSet بيحسب b.GetHashCode().
نفس القيم → نفس الـ hash اللي اتحسب لـ a → نفس الـ bucket.
جوه الـ bucket بيقارن a.Equals(b) (typed، من غير boxing) → true.
الأسهل: استخدم record

public sealed record Money(decimal Amount, string Currency); بيولّد Equals و GetHashCode و == صح أوتوماتيك (شفناه في Part 1). اكتب الـ equality بإيدك بس لما تحتاج تحكم خاص أو class مش record.

الـ Bug الكلاسيكي: Key قابل للتغيير

C#MutableKeyBug.cs
public class Point
{
    public int X, Y;
    public override bool Equals(object? o) => o is Point p && p.X == X && p.Y == Y;
    public override int GetHashCode() => HashCode.Combine(X, Y);
}

var key = new Point { X = 1, Y = 1 };
var map = new Dictionary<Point, string> { [key] = "A" };

key.X = 99;                                    // mutated AFTER insertion: hash changes

Console.WriteLine(map.ContainsKey(key));       // False  (looks in the NEW bucket)
Console.WriteLine(map.ContainsKey(new Point { X = 1, Y = 1 })); // False (right bucket, but Equals fails: stored key is now 99,1)
Console.WriteLine(map.Count);                  // 1 - the entry is "lost" but still occupies memory

إيه اللي حصل؟

الـ entry اتخزنت في bucket محسوب من (1,1). بعد التعديل الـ hash بقى مختلف فالبحث بالـ key المعدّل بيروح bucket تاني ومبيلاقيش حاجة. والبحث بـ (1,1) جديد بيروح الـ bucket الصح بس Equals بتفشل لأن المخزّن بقى (99,1). الـ entry اتحبست. الحل: استخدم keys immutable (records أو readonly struct أو string/int).

Comparers: التحكم من بره الـ type

C#CustomComparer.cs
public sealed class PersonByEmailComparer : IEqualityComparer<Person>
{
    public bool Equals(Person? x, Person? y) =>
        string.Equals(x?.Email, y?.Email, StringComparison.OrdinalIgnoreCase);

    public int GetHashCode(Person p) =>
        StringComparer.OrdinalIgnoreCase.GetHashCode(p.Email);   // must match the Equals above
}

public record Person(string Name, string Email);

var people = new HashSet<Person>(new PersonByEmailComparer())
{
    new("Ali", "ali@x.com"),
    new("Ali Hassan", "ALI@X.COM"),   // considered duplicate -> not added
};
Console.WriteLine(people.Count);       // 1

شرح

الـ IEqualityComparer<T> بيخليك تعرّف المساواة لسياق معين من غير ما تغيّر الـ type نفسه (نفس Person ممكن يتقارن بالإيميل في مكان وبالـ Id في مكان تاني). نفس القاعدة: الـ GetHashCode لازم يستخدم نفس المنطق (هنا case-insensitive) وإلا الـ duplicates مش هتتلقط.

Struct من غير override

الـ ValueType.Equals الافتراضي لو الـ struct فيه reference fields بيستخدم reflection وبيعمل boxing: أبطأ بكتير. لو الـ struct بيتحط في collections اعمله IEquatable<T> أو خليه record struct.

04

الـ Exception Handling

Exceptions · try/catch/finally · filters · rethrow · custom exceptions · cost
Deep dive

الـ exception هي طريقة C#‎ للإبلاغ عن إن العملية معرفتش تنفّذ عقدها (ملف مش موجود، argument غلط، الـ network وقع). الفكرة: بدل ما كل method ترجّع error code وكل caller يفتكر يفحصه، الخطأ بيطلع لفوق في الـ call stack لحد ما حد يعرف يتعامل معاه.

C#ReadPort.cs — specific catches, filter, finally
using System.Diagnostics;

public static class PortReader
{
    public static int ReadPort(string path, bool strict)
    {
        var sw = Stopwatch.StartNew();
        try
        {
            string text = File.ReadAllText(path);          // may throw IOException family
            return int.Parse(text.Trim());                 // may throw FormatException / OverflowException
        }
        catch (FileNotFoundException ex)                   // most specific first
        {
            Console.WriteLine($"Config missing: {ex.FileName}, using default");
            return 8080;
        }
        catch (FormatException) when (!strict)             // exception FILTER
        {
            return 8080;                                   // lenient mode swallows bad content
        }
        catch (IOException ex)                             // broader type after the specific ones
        {
            throw new InvalidOperationException($"Cannot read '{path}'", ex);  // wrap, keep inner
        }
        finally
        {
            Console.WriteLine($"ReadPort took {sw.ElapsedMilliseconds} ms");   // always runs
        }
    }
}

شرح السطور

  1. الـ catch blocks بتتقيّم بالترتيب: أول واحد نوعه بيطابق بيتنفّذ. لو حطيت IOException قبل FileNotFoundException (ابنها) الـ compiler هيرفض لأن التاني مش هيتوصله أبداً.
  2. when (!strict) هو exception filter: الشرط بيتقيّم قبل ما الـ stack يتفكّ. لو false الـ catch بيتعدّى كأنه مش موجود، ومبيتخسرش الـ stack trace ولا الـ state الأصلي.
  3. في الـ IOException بنغلّف الخطأ بـ InvalidOperationException ونمرر الأصلي كـ innerException عشان الـ debugging يشوف السبب الحقيقي.
  4. الـ finally بيتنفّذ في كل الحالات (return عادي، exception اتمسكت، أو exception عدّت لفوق). بنستخدمه للـ cleanup. (للموارد الأحسن using، شفنا ليه في قسم IDisposable.)

إيه اللي بيحصل لما exception بتترمي؟ (Two-pass)

throw new X()in Level3() Pass 1 · FIND handlerwalk up: Level3 → Level2 → Main Pass 2 · UNWINDrun finally blocks, pop frames Level3: no catch Level2: filter false Main: catch ✓ filters run HERE (stack still intact) so a filter can log with the full stack then Pass 2 runs and the catch body executes
الـ CLR بيشتغل على مرحلتين: Pass 1 يدوّر على handler مناسب (ويقيّم الـ filters) من غير ما يفك الـ stack، و Pass 2 يفك الـ stack ويشغّل الـ finally blocks ثم الـ catch

الأهمية: الـ filters بتتنفّذ في Pass 1 قبل الـ finally. وإذا مفيش handler خالص (unhandled) التطبيق بيقع. وأي finally بيرمي exception جديد بيغطّي على الأصلية، فخلّي الـ finally بسيط.

throw; مقابل throw ex;

C#Rethrow.cs
static void Level3() => throw new InvalidOperationException("deep failure");
static void Level2() => Level3();

static void KeepsStack()
{
    try { Level2(); }
    catch (Exception ex) { Console.WriteLine("logging..."); throw; }          // preserves original stack trace
}

static void ResetsStack()
{
    try { Level2(); }
    catch (Exception ex) { throw ex; }                                         // BAD: trace now starts at this line
}

static void Wraps()
{
    try { Level2(); }
    catch (Exception ex) { throw new ApplicationException("operation failed", ex); }  // new exception, inner preserved
}
// KeepsStack  trace: Level3 <- Level2 <- KeepsStack
// ResetsStack trace: ResetsStack only (the real origin is lost)
// Wraps       trace: Wraps, InnerException trace: Level3 <- Level2 <- Wraps

شرح

الـ throw; بيعيد رمي نفس الـ exception بنفس الـ stack trace. أما throw ex; فبيصفّر الـ trace ويخليه يبدأ من السطر ده، فبتضيّع مكان الخطأ الحقيقي. دي من أشهر الأخطاء في code reviews. لو عايز تغلّف، اعمل exception جديدة ومرر القديمة كـ inner.

Custom Exceptions و Guard Clauses و Try-pattern

C#CustomExceptions.cs
public sealed class InsufficientFundsException : Exception
{
    public decimal Balance { get; }
    public decimal Requested { get; }

    public InsufficientFundsException(decimal balance, decimal requested)
        : base($"Balance {balance:C} is lower than requested {requested:C}")
    {
        Balance = balance;
        Requested = requested;
    }
}

public sealed class Account
{
    public decimal Balance { get; private set; }

    public void Withdraw(decimal amount)
    {
        // Guard clauses: fail fast on programmer errors (bad arguments)
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);

        // Domain rule violation: caller may reasonably handle this one
        if (amount > Balance) throw new InsufficientFundsException(Balance, amount);

        Balance -= amount;
    }
}

// Try-pattern for EXPECTED failures (no exception cost):
if (!decimal.TryParse(input, out var parsed))
    return Results.BadRequest("amount is not a number");

شرح

  1. الـ custom exception بتشيل بيانات مفيدة (Balance, Requested) عشان الـ handler ميحتاجش يـ parse الرسالة.
  2. ArgumentOutOfRangeException.ThrowIfNegativeOrZero و ArgumentNullException.ThrowIfNull هي helpers حديثة (‎.NET 8+) بتعمل guard في سطر واحد وبتلتقط اسم الـ parameter أوتوماتيك.
  3. القاعدة: الـ exceptions للحالات الاستثنائية (bug أو فشل خارجي). الحالات المتوقعة في العادي (input المستخدم غلط، key مش موجود) استخدم TryXxx أو Result بدل exception.
التكلفة ومتى تتجنبها

رمي exception وإمساكها أبطأ بكتير من return عادي (بتجمع stack trace وبتعمل unwinding على مرحلتين). مش مشكلة لو نادرة، لكن مشكلة كبيرة لو بتحصل في loop أو في كل request. ما تستخدمهاش للـ control flow. وما تمسكش Exception العامة إلا عند حدود النظام (middleware / top-level handler) للتسجيل والتحويل لـ response، مش وسط المنطق.

في الـ ASP.NET Core بنحوّل الـ exceptions لـ responses موحدة (ProblemDetails) بـ global handler واحد، مش try/catch في كل action. ده متشرح في درس DTOs والـ Validation والـ Errors. وسلوك الـ exceptions جوه الـ async methods (بتتخزن في الـ Task وبتتفجّر عند await) في Part 3.

05

الـ Delegates والـ Events

Delegates · multicast · Func/Action · events · the publisher/subscriber pattern
Deep dive

الـ delegate هو نوع بيمثّل «مرجع لدالة» بشكل type-safe. بدل ما تمرر قيمة، تمرر سلوك. وده أساس الـ callbacks والـ events والـ LINQ والـ lambdas.

C#Delegates.cs
// 1) A delegate TYPE: defines the signature
public delegate int Operation(int a, int b);

// ---- Program.cs ----
static int Add(int a, int b) => a + b;

Operation op = Add;                         // method group -> delegate instance
Console.WriteLine(op(2, 3));                // 5

// 2) You rarely declare your own: use the built-in generic ones
Func<int, int, int> mul = (a, b) => a * b;  // returns a value (last type arg = return type)
Action<string> log = Console.WriteLine;     // returns void
Predicate<int> isEven = n => n % 2 == 0;    // returns bool

// 3) Multicast: += builds an INVOCATION LIST
Action greet = () => Console.WriteLine("hi");
greet += () => Console.WriteLine("hello");
greet += () => throw new Exception("boom");
greet += () => Console.WriteLine("never reached");

try { greet(); }
catch (Exception ex) { Console.WriteLine($"stopped: {ex.Message}"); }
// hi
// hello
// stopped: boom        (the 4th handler never ran)

// Isolate failures by invoking one by one
foreach (var h in greet.GetInvocationList().Cast<Action>())
{
    try { h(); } catch (Exception ex) { Console.WriteLine($"handler failed: {ex.Message}"); }
}

شرح

  1. الـ delegate instance جواه حاجتين: Target (الـ object اللي الميثود تابعة له، أو null للـ static) وMethod (الميثود نفسها). استدعاءه = استدعاء الميثود دي على الـ target.
  2. الـ delegates immutable: += بتعمل delegate جديد بيجمع القديم والجديد (Delegate.Combine) وبتخزنه في المتغير.
  3. في الـ multicast الـ handlers بتتنفذ بالترتيب في نفس الـ thread، وأول exception بتوقف الباقي. لو الـ delegate بيرجّع قيمة بتاخد قيمة آخر handler بس.
  4. Func<…> للي بيرجّع قيمة، Action<…> للـ void، Predicate<T> للـ bool. استخدمهم بدل ما تعرّف delegate types جديدة.

Events: Delegate بقيود

الـ event هو delegate field بحماية: من بره الـ class تقدر بس تعمل += و -= (subscribe/unsubscribe). متقدرش تستدعيه ولا تعمله = null ولا تمسح الـ subscribers التانيين. ده بيخلي الـ publisher هو الوحيد اللي بيقرر إمتى يحصل الـ event.

C#PriceChanged.cs — the standard .NET event pattern
public sealed class PriceChangedEventArgs(decimal oldPrice, decimal newPrice) : EventArgs
{
    public decimal OldPrice { get; } = oldPrice;
    public decimal NewPrice { get; } = newPrice;
}

public sealed class Product
{
    private decimal _price;

    // The event: handlers have the signature (object? sender, PriceChangedEventArgs e)
    public event EventHandler<PriceChangedEventArgs>? PriceChanged;

    public decimal Price
    {
        get => _price;
        set
        {
            if (value == _price) return;
            decimal old = _price;
            _price = value;
            OnPriceChanged(new PriceChangedEventArgs(old, value));
        }
    }

    // Protected virtual raiser + null-conditional Invoke (thread-safe copy of the delegate)
    private void OnPriceChanged(PriceChangedEventArgs e) => PriceChanged?.Invoke(this, e);
}

// ---- Program.cs ----
var product = new Product();

void Audit(object? sender, PriceChangedEventArgs e) =>
    Console.WriteLine($"[audit] {e.OldPrice} -> {e.NewPrice}");

product.PriceChanged += Audit;
product.PriceChanged += (s, e) => Console.WriteLine($"[ui] new price {e.NewPrice}");

product.Price = 10;      // [audit] 0 -> 10   /  [ui] new price 10
product.Price = 10;      // nothing: value unchanged, event not raised
product.PriceChanged -= Audit;
product.Price = 12;      // [ui] new price 12

تتبع التنفيذ

product.Price = 10 بيستدعي الـ setter: القيمة اتغيرت (0 → 10)، فبنحفظ القديمة ونحدّث الحقل.
OnPriceChanged بيعمل PriceChanged?.Invoke(this, e): لو مفيش subscribers القيمة null ومفيش حاجة بتحصل.
الـ invocation list فيها Audit ثم الـ lambda: بيتنادوا بالترتيب وبنفس الـ sender و e.
الـ -= Audit بيشيل الـ handler من الـ list (delegate جديد من غير Audit)، فالتغيير التالي مبيوصلوش.
الـ Memory Leak الشهير

الـ publisher بيمسك reference لكل subscriber (عن طريق الـ Target في الـ delegate). فلو publisher طويل العمر (static event, singleton) و subscriber قصير العمر نسي يعمل -=، الـ subscriber مش هيتجمّع في الـ GC أبداً، ولو الـ handler بيستدعي عليه حاجة هتفضل تتنفذ على object «ميت». الحل: اعمل -= (غالباً في Dispose)، أو استخدم weak events، أو متحطش event على static.

06

الـ Lambda Expressions والـ Closures والـ Local Functions

Lambdas · closures · loop-variable capture · static lambdas · local functions
Practical

الـ lambda هي طريقة مختصرة لكتابة دالة مجهولة الاسم تتحول لـ delegate (أو لـ expression tree). الجزء الحساس مش الـ syntax، هو الـ closure: لما الـ lambda بتستخدم متغيرات من الـ scope اللي حواليها.

C#LambdaForms.cs
Func<int, int> square = x => x * x;                     // expression lambda
Func<int, int, int> add = (a, b) => a + b;              // multiple parameters
Func<int, string> describe = n =>                        // statement lambda
{
    if (n < 0) return "negative";
    return n == 0 ? "zero" : "positive";
};

var twice = (int x) => x * 2;                            // natural type (C# 10): inferred as Func<int,int>
var greet = (string name = "friend") => $"hi {name}";    // default parameter value (C# 12)
Console.WriteLine(greet());                              // hi friend

// Expression lambda targeting Expression<> is DATA, not code: EF Core translates it to SQL
System.Linq.Expressions.Expression<Func<Product, bool>> cheap = p => p.Price < 100;

شرح

نفس الصيغة x => ... بتتحول لـ delegate لو الهدف Func، ولـ expression tree لو الهدف Expression<Func<…>>. الـ expression tree بتمثّل الكود كـ شجرة بيانات يقدر يحللها مكتبة تانية (EF Core بيحوّل p => p.Price < 100 لـ WHERE Price < 100، هنشوف ده في درس EF Core).

الـ Closures: إيه اللي بيحصل فعلاً؟

لما الـ lambda بتستخدم متغير محلي، الـ compiler بيعمل class مخفي (display class) ينقل المتغير ده من الـ stack لحقل جواه (على الـ heap)، وبيخلي الـ lambda ميثود في الـ class ده. فالمتغير بيعيش طول ما الـ delegate عايش.

C#Closure.cs — what the compiler generates (conceptual)
int factor = 3;
Func<int, int> mul = x => x * factor;
factor = 10;
Console.WriteLine(mul(2));   // 20, not 6: the lambda captured the VARIABLE, not its value

// Conceptually the compiler rewrites it as:
sealed class DisplayClass
{
    public int factor;                       // the captured variable lives here (heap)
    public int Lambda(int x) => x * factor;  // the lambda body
}
var closure = new DisplayClass { factor = 3 };   // allocation!
Func<int, int> mul2 = closure.Lambda;            // delegate allocation
closure.factor = 10;                             // writes go to the SAME field the lambda reads

الخلاصة

  1. الـ lambda بتلتقط المتغير نفسه مش قيمته، عشان كده التغيير بعد التعريف بيأثر عليها.
  2. كل closure بتعمل allocation للـ display class + للـ delegate. في hot paths ده بيكلف GC.

فخ الـ Loop Variable

C#LoopCapture.cs
var a = new List<Action>();
for (int i = 0; i < 3; i++) a.Add(() => Console.Write(i + " "));
foreach (var f in a) f();           // 3 3 3   (ONE shared i, ended at 3)
Console.WriteLine();

var b = new List<Action>();
foreach (int n in new[] { 0, 1, 2 }) b.Add(() => Console.Write(n + " "));
foreach (var f in b) f();           // 0 1 2   (foreach: a fresh variable per iteration since C# 5)
Console.WriteLine();

var c = new List<Action>();
for (int i = 0; i < 3; i++) { int copy = i; c.Add(() => Console.Write(copy + " ")); }
foreach (var f in c) f();           // 0 1 2   (copy declared inside the body: one per iteration)

ليه؟

في الـ for المتغير i واحد لكل الـ loop فكل الـ lambdas بتشاور عليه، ولما بتتنفذ بعد الـ loop قيمته 3. في foreach المتغير بيتعمل من جديد لكل iteration فكل lambda ليها نسخة. الحل في for: انسخ لمتغير محلي جوه الـ body.

Static Lambdas والـ Local Functions

C#StaticAndLocal.cs
int offset = 5;

// static lambda (C# 9): the compiler FORBIDS capturing -> guaranteed no closure allocation
Func<int, int> inc = static x => x + 1;
// Func<int,int> bad = static x => x + offset;   // error CS8820

// Local function: a named function inside a method
static IEnumerable<int> Range(int start, int count)
{
    // Validate EAGERLY (iterator bodies only run on first MoveNext):
    if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
    return Core(start, count);

    static IEnumerable<int> Core(int s, int c)      // static local function: no capture
    {
        for (int i = 0; i < c; i++) yield return s + i;
    }
}

// Local functions that do not escape (not converted to delegates) use a struct closure: no heap allocation.
int Sum(int[] xs)
{
    int total = 0;
    foreach (var x in xs) Add(x);
    return total;
    void Add(int v) => total += v;                  // captures 'total' via a struct, not a class
}

شرح

  1. static قبل الـ lambda بيمنع الـ capture: لو حاولت تستخدم offset الـ compiler يرفض. مفيد لتضمن إن مفيش allocation مخفي.
  2. الـ iterator method (yield) مبينفّذش جسمه إلا عند أول MoveNext، فلو حطيت validation جواه هيتأخر. النمط: method عادية بتعمل الـ validation وبترجّع local iterator.
  3. الـ local function اللي مش بتتحول لـ delegate بتتنفذ من غير heap allocation حتى لو فيها capture (الـ compiler بيستخدم struct بالـ ref). عكس الـ lambda.
07

الـ LINQ والـ Deferred Execution

LINQ · query vs method syntax · deferred execution · streaming vs buffering
Deep dive

الـ LINQ (Language Integrated Query) هو مجموعة extension methods على IEnumerable<T> (وعلى IQueryable<T>) بتخليك تعبّر عن «إيه اللي عايزه» (filter, project, group, join) بدل «إزاي أعمله» بـ loops. الفكرة الأهم اللي بتفرّق مبتدئ عن محترف: الـ query مبتتنفذش لما تكتبها، بتتنفذ لما تـ iterate عليها.

C#DeferredExecution.cs — watch WHEN things run
IEnumerable<int> Numbers()
{
    Console.WriteLine("  produce 1"); yield return 1;
    Console.WriteLine("  produce 2"); yield return 2;
    Console.WriteLine("  produce 3"); yield return 3;
}

Console.WriteLine("build query");
var query = Numbers()
    .Where(n => { Console.WriteLine($"  filter {n}"); return n % 2 == 1; })
    .Select(n => { Console.WriteLine($"  select {n}"); return n * 10; });
Console.WriteLine("query built, nothing ran yet");

foreach (var v in query) Console.WriteLine($"got {v}");
// Output:
// build query
// query built, nothing ran yet
//   produce 1
//   filter 1
//   select 1
// got 10
//   produce 2
//   filter 2
//   produce 3
//   filter 3
//   select 3
// got 30
foreachconsumer Selectn * 10 Wheren is odd Numbers()yield return MoveNext()MoveNext()MoveNext() CurrentCurrentCurrent one element travels through the whole chain before the next one is requested
الـ LINQ pipeline بتشتغل بنظام pull: الـ foreach بيطلب عنصر (MoveNext)، والطلب بيرجع للخلف عبر Select ثم Where ثم المصدر، والعنصر بيرجع للأمام واحد واحد

شرح الـ Trace

أول MoveNext من الـ foreach بيروح لـ Select، اللي بيسأل Where، اللي بيسأل Numbers().
الـ iterator بينفّذ لحد أول yield return 1 فبيطبع produce 1 ويقف (state machine بتفتكر مكانها).
Where بيقيّم 1 (فردي ✓) فبيمرره، و Select بيحوّله لـ 10، والـ foreach بيطبع got 10.
الـ MoveNext التاني بيكمل من بعد yield return 1: produce 2، و Where بيرفض 2 (مفيش select ولا got) فبيطلب العنصر اللي بعده مباشرة من غير ما يرجع للـ consumer.

Streaming مقابل Buffering

  • Streaming (بيمرر عنصر عنصر): Where, Select, Take, Skip, SelectMany. بيستهلكوا ذاكرة ثابتة وممكن يشتغلوا على sequences ضخمة.
  • Buffering (لازم يشوف كل المصدر الأول): OrderBy, GroupBy, Reverse, Distinct (جزئياً)، ToList. بيخزنوا كل العناصر في الذاكرة قبل ما يطلّعوا أول نتيجة.

الفخ الأشهر: Multiple Enumeration

C#MultipleEnumeration.cs
int calls = 0;
IEnumerable<int> Source() { calls++; for (int i = 1; i <= 5; i++) yield return i; }

var q = Source().Where(x => x > 2);        // deferred: calls == 0

int count = q.Count();                      // runs Source() -> calls == 1
List<int> list = q.ToList();                // runs Source() AGAIN -> calls == 2
Console.WriteLine(calls);                   // 2

// Fix: materialize once if you need it more than once
var cached = Source().Where(x => x > 2).ToList();   // runs once
int count2 = cached.Count;                          // free: List.Count

ليه ده مهم؟

لو المصدر بيعمل I/O (query على database أو قراءة ملف) كل enumeration هتعيد الـ I/O بالكامل، وممكن النتيجة تتغير بين المرتين. القاعدة: لو هتـ iterate أكتر من مرة، اعمل ToList()/ToArray() مرة واحدة. والـ analyzers (زي CA1851) بتحذرك من ده.

الـ Operators الأساسية في الاستخدام

C#LinqOperators.cs
record Order(int Id, string Customer, decimal Total, string Status);
record Customer(string Name, string City);

// ---- Program.cs ----
var orders = new List<Order>
{
    new(1, "Ali", 120m, "Paid"), new(2, "Sara", 80m, "Pending"),
    new(3, "Ali", 300m, "Paid"), new(4, "Omar", 50m, "Paid"),
};
var customers = new List<Customer> { new("Ali", "Cairo"), new("Sara", "Giza"), new("Omar", "Cairo") };

// Filter + project + sort (method syntax)
var bigPaid = orders.Where(o => o.Status == "Paid" && o.Total >= 100)
                    .OrderByDescending(o => o.Total)
                    .Select(o => new { o.Id, o.Total })
                    .ToList();                                    // [{3,300},{1,120}]

// Group + aggregate
var perCustomer = orders.GroupBy(o => o.Customer)
                        .Select(g => new { Customer = g.Key, Count = g.Count(), Sum = g.Sum(o => o.Total) });
// Ali: 2 / 420,  Sara: 1 / 80,  Omar: 1 / 50

// Join (inner)
var withCity = from o in orders                                    // query syntax (same thing)
               join c in customers on o.Customer equals c.Name
               select new { o.Id, c.City };

// Quantifiers and element operators
bool anyPending = orders.Any(o => o.Status == "Pending");          // true  (stops at first match)
Order top = orders.MaxBy(o => o.Total)!;                           // Id 3 (.NET 6+)
Order? firstSara = orders.FirstOrDefault(o => o.Customer == "Sara");
var pages = orders.Chunk(2);                                       // [[1,2],[3,4]] (.NET 6+)
var byStatus = orders.CountBy(o => o.Status);                      // Paid:3, Pending:1 (.NET 9+)

شرح

  1. الـ query syntax والـ method syntax بيتترجموا لنفس الـ method calls. الـ method syntax أشمل (مفيش query syntax لـ Chunk أو MaxBy).
  2. First بيرمي exception لو مفيش عناصر، FirstOrDefault بيرجّع default، Single بيرمي لو مش واحد بالظبط. اختار حسب العقد اللي عايزه.
  3. Any() أفضل من Count() > 0 لأنه بيوقف عند أول عنصر (والـ Count() ممكن يعدّ كل حاجة لو المصدر مش ICollection).
IEnumerable مقابل IQueryable

نفس الـ syntax، سلوك مختلف جداً: على IEnumerable الـ lambdas بتتنفذ في الذاكرة كـ delegates. على IQueryable (EF Core) الـ lambdas بتتحول لـ expression trees وبتترجم لـ SQL وبتتنفذ في الـ database. التفاصيل في درس LINQ في الـ Databases.

08

الـ Extension Methods

Extension methods · static dispatch · resolution rules · C# 14 extension members
Practical

الـ extension method بتخليك «تضيف» ميثود لنوع موجود (زي string أو IEnumerable<T>) من غير ما تعدّل عليه ولا ترث منه. الـ LINQ كله مبني على كده.

C#Extensions.cs
namespace Company.Extensions;

public static class StringExtensions
{
    // 'this' on the first parameter makes it an extension method
    public static bool IsNullOrBlank(this string? s) => string.IsNullOrWhiteSpace(s);

    public static string Truncate(this string s, int max) =>
        s.Length <= max ? s : s[..max] + "…";
}

public static class EnumerableExtensions
{
    public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : class
    {
        ArgumentNullException.ThrowIfNull(source);   // eager validation
        return Core(source);

        static IEnumerable<T> Core(IEnumerable<T?> src)
        {
            foreach (var x in src)
                if (x is not null) yield return x;
        }
    }
}

// ---- Program.cs ----
using Company.Extensions;                 // the namespace MUST be imported

string? name = null;
Console.WriteLine(name.IsNullOrBlank());                       // True  (no NullReferenceException!)
Console.WriteLine("Extension methods".Truncate(9));            // Extension…
var clean = new string?[] { "a", null, "b" }.WhereNotNull().ToList();   // ["a","b"]

شرح

  1. الـ name.IsNullOrBlank() بيتحول وقت الـ compile لـ StringExtensions.IsNullOrBlank(name): استدعاء static عادي. عشان كده الـ receiver ممكن يكون null من غير exception (على عكس الـ instance method).
  2. مفيش dispatch ديناميكي ولا virtual: الاختيار بيتم وقت الـ compile حسب النوع الظاهري للمتغير.
  3. قواعد الحل: لو في instance method بنفس التوقيع هي اللي بتكسب دايماً. ولازم الـ using للـ namespace. وبتظهر في IntelliSense بعد الـ import.
  4. الـ Core local iterator هو نفس النمط اللي شرحناه: validation فوري ثم تنفيذ مؤجل.
C#‎ 14: Extension Members

مع ‎.NET 10 و C#‎ 14 ظهر الـ extension block اللي بيسمح بـ extension properties وأعضاء static كمان مش بس methods:

C#ExtensionMembers.cs (requires C# 14 / .NET 10 SDK)
public static class EnumerableExtensions14
{
    extension<T>(IEnumerable<T> source)
    {
        public bool IsEmpty => !source.Any();                       // extension PROPERTY
        public IEnumerable<T> Page(int page, int size) =>           // extension method
            source.Skip(page * size).Take(size);
    }
}

// usage: new[] { 1, 2, 3 }.IsEmpty  -> false      items.Page(0, 20)

الـ syntax القديم (this parameter) لسه شغال ومتوافق بالكامل، والـ block الجديد مجرد طريقة أغنى للتعبير.

إمتى تستخدمها؟

للـ helpers اللي بتشتغل على نوع مش بتاعك، وللـ fluent APIs (services.AddMyFeature() في ASP.NET Core هي extension على IServiceCollection). ما تحطش فيها business logic مرتبط بـ entity (ده مكانه الـ entity نفسها)، وتجنب extension على object أو T غير مقيّد لأنها بتلوّث IntelliSense.

09

الـ IDisposable والـ using

IDisposable · using statements · the Dispose pattern · IAsyncDisposable
Deep dive

الـ GC بيدير الذاكرة بس. أما الموارد التانية (file handles، sockets، database connections، native memory) فمش بيعرف إمتى تخلص. الـ IDisposable هو العقد اللي بيقول للـ caller «لما تخلص مني نادي Dispose() وأنا أحرر الموارد دي فوراً».

C#FileLogger.cs — a simple, correct IDisposable
public sealed class FileLogger : IDisposable, IAsyncDisposable
{
    private readonly StreamWriter _writer;
    private bool _disposed;

    public FileLogger(string path) => _writer = new StreamWriter(path, append: true);

    public void Log(string message)
    {
        ObjectDisposedException.ThrowIf(_disposed, this);   // using after dispose is a bug
        _writer.WriteLine($"{DateTime.UtcNow:O} {message}");
    }

    public void Dispose()
    {
        if (_disposed) return;          // idempotent: calling twice must be safe
        _disposed = true;
        _writer.Dispose();              // flushes and closes the file handle
    }

    public async ValueTask DisposeAsync()
    {
        if (_disposed) return;
        _disposed = true;
        await _writer.DisposeAsync();   // async flush, no thread blocked
    }
}

// ---- Program.cs ----
using (var logger = new FileLogger("a.log"))   // classic: disposed at the closing brace
{
    logger.Log("start");
}

using var logger2 = new FileLogger("b.log");   // using declaration: disposed at the end of the enclosing scope
logger2.Log("hello");

await using var logger3 = new FileLogger("c.log");   // awaits DisposeAsync()
logger3.Log("async");

شرح وتتبع

  1. الـ compiler بيحوّل using لـ try { ... } finally { x.Dispose(); } فالـ Dispose بيتنفذ حتى لو حصل exception. ده بالظبط الفرق بين استخدام using وبين تفتكر تكتب Dispose يدوي.
  2. الـ using declaration (using var x) أنضف: مفيش nesting، والـ dispose بيحصل لما الـ scope يخلص بترتيب عكسي للتعريف.
  3. الـ Dispose لازم يكون idempotent (آمن لو اتنادى أكتر من مرة) ومينفعش يرمي exception في الحالات العادية.
  4. await using بيستدعي DisposeAsync للـ resources اللي cleanup بتاعها I/O (flush لـ network أو disk) من غير ما يبلوك thread.

الـ Dispose Pattern الكامل (لما فيه unmanaged resource مباشر)

C#NativeBuffer.cs — full pattern with finalizer (rare!)
using System.Runtime.InteropServices;

public class NativeBuffer : IDisposable
{
    private IntPtr _ptr;                    // unmanaged memory we own DIRECTLY
    private readonly Stream? _log;          // a managed IDisposable we own
    private bool _disposed;

    public NativeBuffer(int size, Stream? log = null)
    {
        _ptr = Marshal.AllocHGlobal(size);
        _log = log;
    }

    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);          // already cleaned: skip the finalizer queue
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed) return;
        if (disposing)
            _log?.Dispose();                // managed members: ONLY when called from Dispose()
        if (_ptr != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(_ptr);      // unmanaged: ALWAYS freed
            _ptr = IntPtr.Zero;
        }
        _disposed = true;
    }

    ~NativeBuffer() => Dispose(disposing: false);   // safety net if the caller forgot
}

ليه الشكل ده؟

  1. الـ finalizer (~NativeBuffer) بيتنادى من الـ GC على thread خاص في وقت غير محدد، ومحدش بيضمن إنه هيتنفذ. فهو safety net مش بديل للـ Dispose.
  2. جوه الـ finalizer (disposing == false) ممنوع تلمس الـ managed members التانية لأنها ممكن تكون اتنضفت قبلك.
  3. الـ GC.SuppressFinalize بيشيل الـ object من finalization queue: الـ objects اللي ليها finalizer بتتأخر في الـ GC (بتعيش جيل زيادة) فمتخليهاش تستنى من غير داعي.
القاعدة العملية

في 99% من الحالات متكتبش finalizer. لو class بتحتفظ بـ IDisposable managed بس: طبّق Dispose() بسيط زي FileLogger (واعمل الـ class sealed). ولو محتاج native handle استخدم SafeHandle بدل IntPtr + finalizer يدوي. والـ DI container بيعمل Dispose للي هو أنشأه، مش للـ instance اللي انت عملتها بإيدك (شفنا ده في درس DI).

10

الـ Garbage Collection وأساسيات الذاكرة

Garbage collection · generations · LOH · finalization · leaks · GC modes
Deep dive

في C#‎ انت بتعمل new ومبتعملش free. الـ GC بيتتبع إمتى الـ object مبقاش حد قادر يوصله وبيرجّع مكانه. فهمه مش رفاهية: هو سبب أغلب مشاكل الـ latency spikes واستهلاك الـ RAM في الـ production.

إزاي الـ GC بيقرر إيه اللي يتمسح؟

  • الـ Roots: المتغيرات المحلية على الـ stack، والـ static fields، والـ CPU registers، والـ GC handles. أي object ممكن توصله من root = حي.
  • Mark: الـ GC بيمشي من الـ roots ويعلّم كل object يقدر يوصله.
  • Sweep/Compact: اللي مش معلّم = زبالة. بيتمسح، والناجيين بيتضغطوا جنب بعض (compaction) فالـ allocation الجاية تبقى مجرد تحريك pointer (سريعة جداً).

الأجيال (Generations)

Gen 0new objectscollected very often Gen 1survived oncebuffer generation Gen 2long-livedcollected rarely (full GC) LOH≥ 85,000 bytescollected with Gen 2 survivesurvive generational hypothesis: most objects die young, so collecting Gen 0 is cheap and frequent
الـ objects الجديدة بتتولد في Gen 0. اللي بينجو من collection بيترقّى لجيل أعلى. الـ objects الكبيرة (85,000 byte فأكتر) بتروح الـ LOH

الفكرة (generational hypothesis): أغلب الـ objects بتعيش لحظات (request objects, temporary strings). فبدل ما الـ GC يفحص الـ heap كله، بيفحص Gen 0 الصغيرة كتير وبسرعة. الـ Gen 2 والـ LOH بتتجمّع نادراً لأنها غالية. وده السبب إن كثرة الـ objects اللي بتعيش «متوسط» (تنجو من Gen 0 وتموت في Gen 2) هي أسوأ نمط.

C#GcObserve.cs
long before = GC.GetAllocatedBytesForCurrentThread();

var list = new List<byte[]>();
for (int i = 0; i < 1000; i++) list.Add(new byte[1024]);        // 1000 small arrays (Gen 0)

long after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"allocated ~ {(after - before) / 1024} KB");       // ~ 1000+ KB
Console.WriteLine($"generation of list: {GC.GetGeneration(list)}");    // 0 (brand new)

var big = new byte[100_000];                                            // >= 85,000 bytes
Console.WriteLine($"big is in generation {GC.GetGeneration(big)}");     // 2 (LOH is logically Gen 2)

Console.WriteLine($"collections: gen0={GC.CollectionCount(0)} gen1={GC.CollectionCount(1)} gen2={GC.CollectionCount(2)}");

// GC.Collect();   // do NOT do this in production code: it breaks the GC's own tuning

شرح

  1. GetAllocatedBytesForCurrentThread بيقيس allocations الـ thread الحالي: طريقة رخيصة لقياس «الكود ده بيعمل كام allocation؟».
  2. الـ byte[100_000] أكبر من حد الـ LOH فبتتحجز هناك، والـ API بتقولك Gen 2 لأن الـ LOH بتتجمّع مع Gen 2 (وبتتضغط بس لو طلبت).
  3. الـ CollectionCount بيوريك كام مرة جمّع كل جيل: لو Gen 2 بيزيد كتير في تطبيق بيشتغل فيه مشكلة allocation.

مشاكل الذاكرة الشائعة (في بيئة بتـ GC)

  • Leak بالـ references: الـ GC مبيمسحش اللي لسه ممكن توصله. أسباب شائعة: static collections/caches بتكبر من غير حد، events مش بتتشال (شفنا)، closures بتمسك objects كبيرة، Timer مش متـ dispose، singleton بيمسك scoped.
  • LOH fragmentation: allocations كبيرة متكررة (new byte[1MB] لكل request) بتولّد Gen 2 GCs غالية. الحل: ArrayPool<T> أو streaming بدل buffers كاملة.
  • Finalizers و handles: الـ objects اللي ليها finalizer بتعيش جيل زيادة.
الإعدادالأفضل لـملاحظات
Workstation (concurrent) GCتطبيقات desktop و CLI وخدمات صغيرةأقل استهلاك للذاكرة؛ الـ background GC بيقلل الـ pauses
Server GCخدمات throughput عالية على أكتر من coreheap و thread لكل core، أعلى throughput لكن أعلى استهلاك للـ RAM
XMLMyApp.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <ServerGarbageCollector>false</ServerGarbageCollector>
    <ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
  </PropertyGroup>
</Project>
إزاي تشخّص بدل ما تخمّن

قيس الأول: dotnet-counters monitor بيعرض gen 0/1/2 GC count وGC heap size وallocation rate لحظياً، و dotnet-gcdump أو dotnet-dump بيوروك مين ماسك الذاكرة. القاعدة: قلّل الـ allocations في الـ hot paths بدل ما تلعب في إعدادات الـ GC (هنشوف الأدوات في Part 3).

11

الـ Span<T> والـ Memory<T>

Span<T> and Memory<T> · slicing without allocation · stackalloc · ArrayPool
Practical

كتير من الـ allocations في الكود اليومي بتجي من إننا بنقص ونقسم البيانات: Substring و Split و ToArray كلهم بيعملوا نسخة جديدة. الـ Span<T> هو نافذة (view) على جزء من الذاكرة موجودة أصلاً (array أو string أو stack) من غير نسخ.

C#SpanBasics.cs
using System.Buffers;
using System.Globalization;
using System.Text;

// 1) Parse "42,19.99" with ZERO allocations: no Substring, no Split
static (int Id, decimal Price) ParseLine(ReadOnlySpan<char> line)
{
    int comma = line.IndexOf(',');
    int id = int.Parse(line[..comma]);                                          // slice = view, not copy
    decimal price = decimal.Parse(line[(comma + 1)..], CultureInfo.InvariantCulture);
    return (id, price);
}

// 2) stackalloc: a small temporary buffer on the STACK (not GC-managed)
static int Utf8Length(string text)
{
    Span<byte> buffer = stackalloc byte[256];
    int written = Encoding.UTF8.GetBytes(text, buffer);      // returns the number of bytes written
    return written;
}

// 3) ArrayPool: rent a LARGE buffer instead of allocating one each time
static void Process()
{
    byte[] rented = ArrayPool<byte>.Shared.Rent(1_000_000);  // may be larger than requested
    try
    {
        Span<byte> work = rented.AsSpan(0, 1_000_000);       // only the part we need
        work.Fill(0);
        // ... use work ...
    }
    finally
    {
        ArrayPool<byte>.Shared.Return(rented);               // ALWAYS return it
    }
}

// ---- Program.cs ----
var (parsedId, parsedPrice) = ParseLine("42,19.99");                     // string converts implicitly to ReadOnlySpan<char>
Console.WriteLine($"{parsedId} / {parsedPrice}");                      // 42 / 19.99
Console.WriteLine(Utf8Length("héllo"));                      // 6  (é takes 2 bytes in UTF-8)

شرح وتتبع

ParseLine("42,19.99"): الـ string بيتحوّل لـ ReadOnlySpan<char> من غير نسخ (pointer + length).
IndexOf(',') بيرجّع 2. line[..2] بيعمل span جديد بيشاور على نفس الذاكرة (أول حرفين) من غير allocation.
int.Parse(span) بيقرا الأرقام مباشرة من الذاكرة الأصلية → 42، و line[3..] → "19.99" → 19.99m.
النتيجة: صفر allocations مقابل Split اللي كانت هتعمل array + 2 strings.
  1. الـ stackalloc بيحجز على الـ stack وبيتحرر أوتوماتيك لما الميثود تخلص. استخدمه لـ buffers صغيرة (مئات الـ bytes) فقط وإلا خطر Stack Overflow.
  2. الـ ArrayPool.Rent ممكن يرجّع array أكبر من المطلوب ومحتوياتها قد تكون «قديمة»؛ فاشتغل في الـ slice اللي محتاجه وارجّعها في finally.

Span مقابل Memory: ليه الاتنين؟

Span<T> / ReadOnlySpan<T>

هو ref struct: عايش على الـ stack بس. يعني مينفعش يكون field في class عادية، ولا يتخزن في collection، ولا يتعمله boxing، ولا يتستخدم عبر await أو yield. بالمقابل هو الأسرع وبيدعم stackalloc.

Memory<T> / ReadOnlyMemory<T>

struct عادي ممكن يتخزن في field ويعدّي عبر await. بتاخد منه .Span وقت الشغل الفعلي. بيستخدم في الـ async I/O (Stream.ReadAsync(Memory<byte>)).

C#MemoryAsync.cs
static async Task<int> FillAsync(Stream stream, Memory<byte> buffer, CancellationToken ct)
{
    // Memory<T> can cross the await; Span<T> could not
    int read = await stream.ReadAsync(buffer, ct);
    Parse(buffer.Span[..read]);                  // get the Span only when doing synchronous work
    return read;
}

static void Parse(ReadOnlySpan<byte> data) { /* synchronous parsing */ }
C#‎ 14: first-class span support

في C#‎ 14 الـ conversions بين T[] و Span<T>/ReadOnlySpan<T> بقت implicit أكتر، فكتير من الـ overloads (MemoryExtensions) بتشتغل مباشرة على الـ arrays من غير .AsSpan(). لا تحسّن بـ Span قبل ما تقيس: فايدته الحقيقية في الـ hot paths (parsing, protocols, serialization).

12

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

Common mistakes and troubleshooting
Pitfalls
الخطأالعَرَضالسببالحل
Override Equals من غير GetHashCodeعنصر موجود وبـ Contains بيرجّع false، تحذير CS0659الـ hash لسه reference-based فبيروح bucket مختلفاعمل override للاتنين بنفس الحقول، أو استخدم record
Key قابل للتعديل في Dictionary/HashSetentry «اختفت» بعد تعديل propertyالـ hash اتغير بعد الإدخالkeys immutable (record/readonly struct/string/int)
throw ex;الـ stack trace بيبدأ من الـ catchبيصفّر الـ tracethrow; أو غلّف مع inner exception
Catch Exception وتجاهلها (catch {})bugs صامتة وبيانات غلطالخطأ اتبلع من غير تسجيل ولا معالجةامسك أنواع محددة، سجّل، أو اسمح لها تعدي لفوق
Multiple enumeration لـ IEnumerablequery بتتنفذ مرتين (DB hit مضاعف)deferred executionToList() مرة واحدة
Capture لمتغير الـ for في lambdaكل الـ lambdas بترجّع نفس القيمةمتغير واحد مشتركانسخه لمتغير محلي جوه الـ body
نسيان -= على event طويل العمرRAM بيكبر و handlers بتتنفذ على objects قديمةالـ publisher بيمسك الـ subscriberunsubscribe في Dispose، أو weak events
إنشاء IDisposable من غير usingfile locked / connection pool exhaustedالـ GC مبيحرّرش الـ handles في الوقت المناسبusing / await using دايماً
استدعاء GC.Collect() بإيدكpauses أكبر وأداء أسوأبتكسر ضبط الـ GC الذاتي وبترقّي objects قبل أوانهاشيلها وحلّ سبب الـ allocations
Span<T> في async methodcompile error CS4012ref struct مينفعش يعيش عبر awaitاستخدم Memory<T> وخد .Span وقت الحاجة

إزاي تـ debug؟

  1. سلوك collections غريب: اطبع GetHashCode() لعنصرين المفروض متساويين، وراجع إن Equals و GetHashCode بيستخدموا نفس الحقول.
  2. Exception مش واضحة: اقرا InnerException بالتسلسل، وفعّل «break on first-chance exception» في الـ debugger.
  3. RAM بيزيد: خد dotnet-gcdump مرتين وقارن أكتر الأنواع نمواً، وشوف مين ماسكها (static/event/cache).
13

الأداء والمفاضلات

Performance and trade-offs
Basics
  • Collections: اختار حسب العملية الأكتر تكراراً. List.Contains في loop = O(n²)، حوّلها لـ HashSet. حدد capacity لما تعرف الحجم. للـ lookup ثابت بعد الـ startup جرّب FrozenDictionary.
  • LINQ: مريح وغالباً كفاية. في الـ hot paths الجوانب: allocation للـ delegates والـ enumerators، وبطء نسبي مقارنة بـ for مباشر. قيس بـ BenchmarkDotNet قبل ما تستبدله.
  • Closures: كل capture = allocation. استخدم static lambdas والـ local functions في المسارات الساخنة.
  • Exceptions: غالية في مسار الفشل، فمتعتمدش عليها في الـ flow الطبيعي. استخدم TryXxx.
  • GC: التكلفة مرتبطة بعدد الـ allocations ومعدل نجاة الـ objects، مش بحجم الـ heap فقط. قلّل الـ short-lived allocations، وتجنب الـ LOH المتكرر.
  • Span/ArrayPool: أكبر فايدة في parsing و protocols. ضيف تعقيد الكود فقط لما القياس يبرر.
القرارالاختيار الأبسطالاختيار الأسرعمتى تنتقل؟
تقسيم نصSplit / SubstringReadOnlySpan<char> + slicingparsing بحجم كبير أو في hot path
معالجة sequenceLINQfor loop على array/spanprofiler بيوريك LINQ هو الاختناق
buffer مؤقتnew byte[n]stackalloc (صغير) / ArrayPool (كبير)allocation rate عالي أو LOH GCs
14

Knowledge Check

Takeaways · conceptual questions · code reading · interview questions
Basics

أهم النقاط

  • الـ generics في C#‎ reified: كود مخصص لكل value type (بدون boxing) وكود مشترك للـ reference types. الـ constraints بتفتح لك الأعضاء، والـ variance (out/in) بس على interfaces/delegates.
  • Dictionary = buckets + entries؛ الـ O(1) متوقف على جودة GetHashCode. لو override Equals لازم GetHashCode، والـ keys تكون immutable.
  • throw; بيحافظ على الـ stack trace. الـ exceptions للحالات الاستثنائية، و TryXxx للمتوقعة.
  • الـ event هو delegate بحماية؛ الـ publisher بيمسك الـ subscribers، فاعمل unsubscribe.
  • الـ lambda بتلتقط المتغير مش قيمته (closure = allocation). static lambda بتمنع الـ capture.
  • الـ LINQ مؤجل التنفيذ: مفيش حاجة بتشتغل قبل الـ enumeration، والـ enumeration المتعددة بتكرر الشغل.
  • using = try/finally. الـ GC بيدير الذاكرة بس، والـ IDisposable للـ resources الباقية. متكتبش finalizer غير لو لازم.
  • الـ GC generational: Gen 0 رخيصة ومتكررة، Gen 2/LOH غالية. قلّل الـ allocations ومتستدعيش GC.Collect().
  • Span<T> للـ slicing من غير نسخ (stack-only)، و Memory<T> لو محتاج async أو تخزين.

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

ليه List<Dog> مينفعش تتحول لـ List<Animal> بس IEnumerable<Dog> ينفع؟

لأن List<T> بتقرا وتكتب (invariant): لو اتحولت لـ List<Animal> هتقدر تضيف Cat في list كلاب. أما IEnumerable<out T> للقراءة فقط (covariant) فالتحويل آمن لأن مفيش طريقة لإدخال عنصر خاطئ.

إيه اللي بيحصل بالظبط لما Dictionary يدوّر على key؟

بيحسب GetHashCode()، ويطلع الـ bucket بـ mod على حجم الـ array، وبيمشي على سلسلة الـ entries في الـ bucket (عن طريق next) ويقارن الـ hash ثم Equals. متوسط O(1) لو الـ hash موزع كويس، و O(n) في أسوأ حالة (collisions كتير).

الفرق بين throw و throw ex؟ وإمتى تستخدم exception filter؟

throw; بيحافظ على الـ stack trace الأصلي و throw ex; بيصفّره. الـ filter (when) بيتقيّم في Pass 1 قبل فك الـ stack فبيحافظ على الـ state ومناسب للتسجيل أو للتفرقة بين حالات من نفس النوع (مثلاً status code) من غير ما تمسك وتعيد الرمي.

ليه الـ lambda ممكن تعمل allocation؟ وإزاي تتجنبه؟

لما بتلتقط متغيرات محلية الـ compiler بيعمل display class (heap) و delegate جديد. تتجنبه بـ static lambda (بتمنع الـ capture) أو بتمرير الحالة كـ parameter، أو local function (struct closure) لو مش هتتحول لـ delegate.

ليه الـ finalizer مش بديل عن Dispose؟

مفيش ضمان لوقت (أو حتى حدوث) تنفيذه، وهو بيتنفذ على thread الـ finalizer بعد ما الـ object يعيش جيل زيادة. الـ Dispose بيحرر الموارد فوراً وبشكل حتمي، والـ finalizer مجرد safety net للـ native resources.

قراءة كود

C#Predict the output (1)
var list = new List<int> { 1, 2, 3 };
var q = list.Where(x => x > 1);
list.Add(4);
Console.WriteLine(q.Count());
ما الناتج؟ ولماذا؟

3. الـ Where مؤجلة التنفيذ فمبتتقيّم إلا عند Count()، ووقتها القائمة فيها 1,2,3,4 فالمطابق هو 2,3,4.

C#What's wrong here? (2)
public class Key
{
    public string Id = "";
    public override bool Equals(object? o) => o is Key k && k.Id == Id;
}

var set = new HashSet<Key> { new Key { Id = "a" } };
Console.WriteLine(set.Contains(new Key { Id = "a" }));
إيه المشكلة وإيه الناتج المتوقع؟

الـ class عمل override لـ Equals من غير GetHashCode (تحذير CS0659). الـ hash لسه reference-based فالـ object الجديد ليه hash مختلف على الأغلب فبيروح bucket تاني، والناتج غالباً False رغم إن Equals هترجّع true لو اتقارنوا مباشرة. الحل: override GetHashCode() => Id.GetHashCode() (أو استخدم record).

C#Predict the output (3)
static int F()
{
    try { return 1; }
    finally { Console.Write("F "); }
}
Console.WriteLine(F());
ما الناتج؟

F 1. قيمة الـ return اتحسبت (1) وفضلت محفوظة، ثم اتنفذ الـ finally (طبع F ) قبل ما الميثود ترجع فعلاً، ثم طُبع الـ 1.

أسئلة مقابلات شائعة

اشرح الفرق بين IEnumerable و IQueryable وإمتى الـ query بتتنفذ؟

الاتنين deferred. IEnumerable بتنفذ الـ lambdas في الذاكرة كـ delegates، و IQueryable بتحوّلها لـ expression tree يترجمها provider (زي EF Core) لـ SQL. التنفيذ بيحصل عند الـ enumeration (foreach, ToList, Count…) وليس عند كتابة الـ query. ومن هنا خطر الـ multiple enumeration.

إزاي تتعامل مع memory leak في تطبيق ‎.NET؟

أقيس الأول: dotnet-counters للـ heap size و GC counts، ثم dotnet-gcdump مرتين وأقارن الأنواع الأكتر نمواً وأتتبع الـ root اللي ماسكها. المشتبه فيهم: static collections/caches من غير حد، events مش بتتشال، singleton ماسك scoped، timers، و IDisposable متنساش.

امتى تستخدم struct و Span بدل class و arrays؟

الـ struct للقيم الصغيرة immutable لتقليل الـ allocations ومع الـ equality المناسبة. والـ Span للـ slicing والـ parsing من غير نسخ في المسارات الساخنة، مع قيد إنه stack-only (مفيش async)، واستخدام Memory لو محتاج يعدّي عبر await. وفي الحالتين: قيس بـ BenchmarkDotNet قبل ما تعقّد الكود.

الجزء اللي جاي (Part 3) بيغطي async/await والـ Task والـ threading والـ Channels والـ reflection والـ serialization والـ source generators والـ dotnet CLI والـ debugging.

↗

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

References & further reading

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

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

خريطة التغطية: 12 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapGenerics and Generic Constraints§01
RoadmapCollections and Collection Interfaces§02
RoadmapEquality and GetHashCode()§03
RoadmapException Handling§04
RoadmapDelegates and Events§05
RoadmapLambda Expressions§06
RoadmapLINQ§07
RoadmapExtension Methods§08
RoadmapIDisposable and using§09
RoadmapGarbage Collection and Memory Basics§10
SuggestedSpan<T> and Memory<T> basics§11
SuggestedLocal functions and static lambdas§06

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

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