الـ Generics والـ Constraints والـ Variance
قبل الـ generics (قبل C# 2) لو عايز collection تشيل أي نوع كنت بتستخدم ArrayList اللي بتخزن object. النتيجة: boxing للـ value types، و casts في كل قراءة، وأخطاء النوع بتطلع وقت التشغيل مش وقت الـ compile. الـ generics حلّت ده بإنك تكتب الكود مرة واحدة وانت سايب النوع كـ parameter.
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[]شرح الكود
- الـ
ArrayListبتاخدobjectفالـ10بيتعمله boxing (allocation على الـ heap، شفنا ده في Part 1). والقراءة(int)old[0]بتعمل unboxing. - السطر التاني بيدخل
stringفي collection المفروض فيها أرقام: الـ compiler مبيعترضش، والانفجار بيحصل بعدين في الـ production. - الـ
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 : struct | non-nullable value type | T? = Nullable<T>، ومنع boxing |
where T : notnull | أي نوع non-nullable | تحذيرات الـ nullable analysis |
where T : new() | لازم parameterless constructor public | new T() |
where T : BaseClass | يرث من class معين | أعضاء الـ BaseClass |
where T : IComparable<T> | يطبّق interface | استدعاء أعضاء الـ interface |
where T : unmanaged | struct من غير أي references جواه | sizeof, stackalloc, pointers |
where T : allows ref struct (C# 13) | يسمح بـ Span<T> كـ type argument | generics مع ref structs |
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
- FindById: من غير
where T : IEntityالسطرitem.Idمش هيتعمله compile لأنTمجهول. والـdefaultبيرجّعnullللـ classes وصفر للـ structs ولذلك الـ return typeT?. - Create: الـ
new()constraint هو الوحيد اللي بيسمح بـnew T(). (تحت الغطا بيستخدمActivator.CreateInstanceفهو أبطأ منnewالعادية.) - 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).Sum<int> مخصوصة (لأن int value type)، و T.Zero بتتحول لـ 0 ثابت.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 كلاب.
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شرح
- السطر التاني آمن لأن
IEnumerable<out T>مفيهوش غير قراءة: مفيش طريقة تدخلCatجواه. - الـ
Action<Animal>تقدر تستخدمها مكانAction<Dog>لأن أي حاجة بتتعامل مع Animal بتتعامل مع Dog (الاتجاه معكوس = contra). - الـ variance بتشتغل بس مع reference types كـ type arguments؛
IEnumerable<int>مش بيتحول لـIEnumerable<object>لأنه محتاج boxing. - الـ arrays covariant لأسباب تاريخية، وده اللي بيخلي آخر سطر يترمي عليه exception وقت التشغيل. استخدم
IReadOnlyList<T>بدلها لما تحتاج variance آمن.
الـ Collections والـ Collection Interfaces
اختيار الـ collection الغلط هو من أكتر أسباب البطء في كود الـ backend: List.Contains جوه loop بتحوّل O(n) لـ O(n²)، و dictionary بـ key فيه hash سيئ بتحوّل الـ O(1) لـ O(n). عشان تختار صح لازم تفهم هي بتخزن إزاي.
List<T> من جوه: Array بتكبر
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شرح
- الـ
List<T>بتحتفظ بـ array داخليةT[]وعدّادCount. الـCapacityهو حجم الـ array. - أول
Addبيعمل array حجمها 4. لما تمتلي، بتتعمل array بالضعف وبيتنسخ فيها كل العناصر ثم بتتلغى القديمة. - عشان كده
Addهو O(1) amortized: غالباً O(1) وأحياناً O(n) بس نادر. بينماInsertفي الأول وRemoveوContainsكلهم O(n). - لو تعرف الحجم تقريباً مسبقاً مرر
capacityوتفادى النسخ والضغط على الـ GC.
Dictionary<TKey,TValue> من جوه
الـ dictionary عبارة عن hash table بـ chaining مبني على arrays: array للـ buckets و array للـ entries. الـ lookup بيمشي كده:
- الـ
GetHashCodeبيحوّل المفتاح لرقم، والـ bucket = الرقم mod حجم الـ array (حجم بيكون عدد أولي). كل bucket بيشاور على أول entry، وكل entry فيهnextللـ entry اللي بعده في نفس الـ bucket (collision). - لو المفاتيح hash-ها كويس (موزّع) فالسلاسل قصيرة جداً والـ lookup O(1) متوسط. لو الـ
GetHashCodeبيرجّع نفس الرقم لكل حاجة، كل المفاتيح تتكوّم في bucket واحد والـ lookup بقى O(n). - لما الـ entries تخلص، الـ dictionary بتكبّر (resize) وبتعيد توزيع كل المفاتيح: عملية تقيلة، فمرر
capacityلو تعرف الحجم.
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}");شرح
- الـ
StringComparer.OrdinalIgnoreCaseبيغيّر تعريف المساواة والـ hash مع بعض فـ"APPLE"بتلاقي"apple". من غيره المقارنة case-sensitive. - الـ indexer القراءة بيرمي
KeyNotFoundException، فاستخدمTryGetValueلما الـ key ممكن يكون غايب. ContainsKeyثم indexer = حسابين للـ hash.TryGetValue= حساب واحد.
باقي الـ Collections: إمتى تستخدم إيه
| النوع | التخزين الداخلي | العمليات الأساسية | استخدمه لما |
|---|---|---|---|
List<T> | array بتكبر | index O(1) · Add O(1)* · Contains/Remove O(n) | الافتراضي لأي sequence |
Dictionary<K,V> | hash table | get/set/remove O(1) avg | lookup بالـ key |
HashSet<T> | hash table (keys بس) | Add/Contains O(1) avg · عمليات المجموعات | uniqueness و membership |
Queue<T> | circular array | Enqueue/Dequeue O(1) | FIFO (jobs, BFS) |
Stack<T> | array | Push/Pop O(1) | LIFO (undo, DFS) |
PriorityQueue<E,P> | array-backed min-heap | Enqueue/Dequeue O(log n) | scheduling، أقصر مسار |
LinkedList<T> | doubly linked nodes | insert/remove عند node معروفة O(1) | نادراً جداً (cache-unfriendly) |
SortedDictionary<K,V> / SortedSet<T> | red-black tree | O(log n) + ترتيب | محتاج iteration مرتب |
FrozenDictionary / FrozenSet (.NET 8) | مُحسّنة للقراءة بعد البناء | lookup أسرع، بناء أبطأ | lookup tables ثابتة بعد الـ startup |
ConcurrentDictionary / ImmutableArray | thread-safe / immutable | — | مشاركة بين threads / snapshots |
الـ data structures نفسها (الـ trees والـ heaps والـ hash tables) متشرحة بالتفصيل في درس Data Structures، هنا بنركز على استخدامها في .NET.
الـ Collection Interfaces: صمّم الـ API بيها
// 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شرح
- Accept general، return specific-but-safe: المعاملات بنيجي بأقل interface مطلوب (
IEnumerable<T>) عشان نقبل أي مصدر. والـ return بيكونIReadOnlyList<T>عشان نحمي الـ state الداخلي. - تنبيه:
IReadOnlyListمجرد view على نفس الـ list؛ لو المستدعي عمل cast لـList<Order>هيقدر يعدّل. لو الحماية الصارمة مطلوبة استخدمImmutableArrayأوAsReadOnly(). - الـ
List<T>جواها رقم_versionبيزيد مع كل تعديل، والـ enumerator بيقارن بيه في كلMoveNext. ده سبب الـ exception في آخر مثال. الحل: iterate على نسخة، أو استخدمRemoveAll(predicate).
الـ Equality والـ GetHashCode
في 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 لواحد منهم لازم تعمل للتاني.
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)شرح وتتبع
- الـ
Equals(Money?)بيقارن نفس الحقول اللي بنحسب منها الـ hash:AmountوCurrency. HashCode.Combineبيدمج الـ hashes بشكل موزّع كويس ومتطوّر لكل process (مش ثابت بين التشغيلات، فمتخزنهوش في ملف أو database).- الـ
==بيتأكد منnullالأول قبل ما يستدعيEqualsعشان ميحصلش NullReferenceException.
set.Contains(b): الـ HashSet بيحسب b.GetHashCode().a → نفس الـ bucket.a.Equals(b) (typed، من غير boxing) → true.public sealed record Money(decimal Amount, string Currency); بيولّد Equals و GetHashCode و == صح أوتوماتيك (شفناه في Part 1). اكتب الـ equality بإيدك بس لما تحتاج تحكم خاص أو class مش record.
الـ Bug الكلاسيكي: Key قابل للتغيير
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
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 مش هتتلقط.
الـ ValueType.Equals الافتراضي لو الـ struct فيه reference fields بيستخدم reflection وبيعمل boxing: أبطأ بكتير. لو الـ struct بيتحط في collections اعمله IEquatable<T> أو خليه record struct.
الـ Exception Handling
الـ exception هي طريقة C# للإبلاغ عن إن العملية معرفتش تنفّذ عقدها (ملف مش موجود، argument غلط، الـ network وقع). الفكرة: بدل ما كل method ترجّع error code وكل caller يفتكر يفحصه، الخطأ بيطلع لفوق في الـ call stack لحد ما حد يعرف يتعامل معاه.
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
}
}
}شرح السطور
- الـ
catchblocks بتتقيّم بالترتيب: أول واحد نوعه بيطابق بيتنفّذ. لو حطيتIOExceptionقبلFileNotFoundException(ابنها) الـ compiler هيرفض لأن التاني مش هيتوصله أبداً. when (!strict)هو exception filter: الشرط بيتقيّم قبل ما الـ stack يتفكّ. لو false الـ catch بيتعدّى كأنه مش موجود، ومبيتخسرش الـ stack trace ولا الـ state الأصلي.- في الـ
IOExceptionبنغلّف الخطأ بـInvalidOperationExceptionونمرر الأصلي كـinnerExceptionعشان الـ debugging يشوف السبب الحقيقي. - الـ
finallyبيتنفّذ في كل الحالات (return عادي، exception اتمسكت، أو exception عدّت لفوق). بنستخدمه للـ cleanup. (للموارد الأحسنusing، شفنا ليه في قسم IDisposable.)
إيه اللي بيحصل لما exception بتترمي؟ (Two-pass)
الأهمية: الـ filters بتتنفّذ في Pass 1 قبل الـ finally. وإذا مفيش handler خالص (unhandled) التطبيق بيقع. وأي finally بيرمي exception جديد بيغطّي على الأصلية، فخلّي الـ finally بسيط.
throw; مقابل throw ex;
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
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");شرح
- الـ custom exception بتشيل بيانات مفيدة (
Balance,Requested) عشان الـ handler ميحتاجش يـ parse الرسالة. ArgumentOutOfRangeException.ThrowIfNegativeOrZeroوArgumentNullException.ThrowIfNullهي helpers حديثة (.NET 8+) بتعمل guard في سطر واحد وبتلتقط اسم الـ parameter أوتوماتيك.- القاعدة: الـ 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.
الـ Delegates والـ Events
الـ delegate هو نوع بيمثّل «مرجع لدالة» بشكل type-safe. بدل ما تمرر قيمة، تمرر سلوك. وده أساس الـ callbacks والـ events والـ LINQ والـ lambdas.
// 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}"); }
}شرح
- الـ delegate instance جواه حاجتين: Target (الـ object اللي الميثود تابعة له، أو null للـ static) وMethod (الميثود نفسها). استدعاءه = استدعاء الميثود دي على الـ target.
- الـ delegates immutable:
+=بتعمل delegate جديد بيجمع القديم والجديد (Delegate.Combine) وبتخزنه في المتغير. - في الـ multicast الـ handlers بتتنفذ بالترتيب في نفس الـ thread، وأول exception بتوقف الباقي. لو الـ delegate بيرجّع قيمة بتاخد قيمة آخر handler بس.
Func<…>للي بيرجّع قيمة،Action<…>للـ void،Predicate<T>للـ bool. استخدمهم بدل ما تعرّف delegate types جديدة.
Events: Delegate بقيود
الـ event هو delegate field بحماية: من بره الـ class تقدر بس تعمل += و -= (subscribe/unsubscribe). متقدرش تستدعيه ولا تعمله = null ولا تمسح الـ subscribers التانيين. ده بيخلي الـ publisher هو الوحيد اللي بيقرر إمتى يحصل الـ event.
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 ومفيش حاجة بتحصل.Audit ثم الـ lambda: بيتنادوا بالترتيب وبنفس الـ sender و e.-= Audit بيشيل الـ handler من الـ list (delegate جديد من غير Audit)، فالتغيير التالي مبيوصلوش.الـ publisher بيمسك reference لكل subscriber (عن طريق الـ Target في الـ delegate). فلو publisher طويل العمر (static event, singleton) و subscriber قصير العمر نسي يعمل -=، الـ subscriber مش هيتجمّع في الـ GC أبداً، ولو الـ handler بيستدعي عليه حاجة هتفضل تتنفذ على object «ميت». الحل: اعمل -= (غالباً في Dispose)، أو استخدم weak events، أو متحطش event على static.
الـ Lambda Expressions والـ Closures والـ Local Functions
الـ lambda هي طريقة مختصرة لكتابة دالة مجهولة الاسم تتحول لـ delegate (أو لـ expression tree). الجزء الحساس مش الـ syntax، هو الـ closure: لما الـ lambda بتستخدم متغيرات من الـ scope اللي حواليها.
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 عايش.
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الخلاصة
- الـ lambda بتلتقط المتغير نفسه مش قيمته، عشان كده التغيير بعد التعريف بيأثر عليها.
- كل closure بتعمل allocation للـ display class + للـ delegate. في hot paths ده بيكلف GC.
فخ الـ Loop Variable
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
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
}شرح
staticقبل الـ lambda بيمنع الـ capture: لو حاولت تستخدمoffsetالـ compiler يرفض. مفيد لتضمن إن مفيش allocation مخفي.- الـ iterator method (
yield) مبينفّذش جسمه إلا عند أولMoveNext، فلو حطيت validation جواه هيتأخر. النمط: method عادية بتعمل الـ validation وبترجّع local iterator. - الـ local function اللي مش بتتحول لـ delegate بتتنفذ من غير heap allocation حتى لو فيها capture (الـ compiler بيستخدم struct بالـ
ref). عكس الـ lambda.
الـ LINQ والـ Deferred Execution
الـ LINQ (Language Integrated Query) هو مجموعة extension methods على IEnumerable<T> (وعلى IQueryable<T>) بتخليك تعبّر عن «إيه اللي عايزه» (filter, project, group, join) بدل «إزاي أعمله» بـ loops. الفكرة الأهم اللي بتفرّق مبتدئ عن محترف: الـ query مبتتنفذش لما تكتبها، بتتنفذ لما تـ iterate عليها.
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شرح الـ Trace
MoveNext من الـ foreach بيروح لـ Select، اللي بيسأل Where، اللي بيسأل Numbers().yield return 1 فبيطبع produce 1 ويقف (state machine بتفتكر مكانها).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
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 الأساسية في الاستخدام
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+)شرح
- الـ query syntax والـ method syntax بيتترجموا لنفس الـ method calls. الـ method syntax أشمل (مفيش query syntax لـ
ChunkأوMaxBy). Firstبيرمي exception لو مفيش عناصر،FirstOrDefaultبيرجّع default،Singleبيرمي لو مش واحد بالظبط. اختار حسب العقد اللي عايزه.Any()أفضل منCount() > 0لأنه بيوقف عند أول عنصر (والـCount()ممكن يعدّ كل حاجة لو المصدر مش ICollection).
نفس الـ syntax، سلوك مختلف جداً: على IEnumerable الـ lambdas بتتنفذ في الذاكرة كـ delegates. على IQueryable (EF Core) الـ lambdas بتتحول لـ expression trees وبتترجم لـ SQL وبتتنفذ في الـ database. التفاصيل في درس LINQ في الـ Databases.
الـ Extension Methods
الـ extension method بتخليك «تضيف» ميثود لنوع موجود (زي string أو IEnumerable<T>) من غير ما تعدّل عليه ولا ترث منه. الـ LINQ كله مبني على كده.
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"]شرح
- الـ
name.IsNullOrBlank()بيتحول وقت الـ compile لـStringExtensions.IsNullOrBlank(name): استدعاء static عادي. عشان كده الـ receiver ممكن يكونnullمن غير exception (على عكس الـ instance method). - مفيش dispatch ديناميكي ولا virtual: الاختيار بيتم وقت الـ compile حسب النوع الظاهري للمتغير.
- قواعد الحل: لو في instance method بنفس التوقيع هي اللي بتكسب دايماً. ولازم الـ
usingللـ namespace. وبتظهر في IntelliSense بعد الـ import. - الـ
Corelocal iterator هو نفس النمط اللي شرحناه: validation فوري ثم تنفيذ مؤجل.
مع .NET 10 و C# 14 ظهر الـ extension block اللي بيسمح بـ extension properties وأعضاء static كمان مش بس methods:
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.
الـ IDisposable والـ using
الـ GC بيدير الذاكرة بس. أما الموارد التانية (file handles، sockets، database connections، native memory) فمش بيعرف إمتى تخلص. الـ IDisposable هو العقد اللي بيقول للـ caller «لما تخلص مني نادي Dispose() وأنا أحرر الموارد دي فوراً».
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");شرح وتتبع
- الـ compiler بيحوّل
usingلـtry { ... } finally { x.Dispose(); }فالـDisposeبيتنفذ حتى لو حصل exception. ده بالظبط الفرق بين استخدامusingوبين تفتكر تكتب Dispose يدوي. - الـ using declaration (
using var x) أنضف: مفيش nesting، والـ dispose بيحصل لما الـ scope يخلص بترتيب عكسي للتعريف. - الـ
Disposeلازم يكون idempotent (آمن لو اتنادى أكتر من مرة) ومينفعش يرمي exception في الحالات العادية. await usingبيستدعيDisposeAsyncللـ resources اللي cleanup بتاعها I/O (flush لـ network أو disk) من غير ما يبلوك thread.
الـ Dispose Pattern الكامل (لما فيه unmanaged resource مباشر)
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
}ليه الشكل ده؟
- الـ finalizer (
~NativeBuffer) بيتنادى من الـ GC على thread خاص في وقت غير محدد، ومحدش بيضمن إنه هيتنفذ. فهو safety net مش بديل للـDispose. - جوه الـ finalizer (
disposing == false) ممنوع تلمس الـ managed members التانية لأنها ممكن تكون اتنضفت قبلك. - الـ
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).
الـ Garbage Collection وأساسيات الذاكرة
في 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)
الفكرة (generational hypothesis): أغلب الـ objects بتعيش لحظات (request objects, temporary strings). فبدل ما الـ GC يفحص الـ heap كله، بيفحص Gen 0 الصغيرة كتير وبسرعة. الـ Gen 2 والـ LOH بتتجمّع نادراً لأنها غالية. وده السبب إن كثرة الـ objects اللي بتعيش «متوسط» (تنجو من Gen 0 وتموت في Gen 2) هي أسوأ نمط.
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شرح
GetAllocatedBytesForCurrentThreadبيقيس allocations الـ thread الحالي: طريقة رخيصة لقياس «الكود ده بيعمل كام allocation؟».- الـ
byte[100_000]أكبر من حد الـ LOH فبتتحجز هناك، والـ API بتقولك Gen 2 لأن الـ LOH بتتجمّع مع Gen 2 (وبتتضغط بس لو طلبت). - الـ
CollectionCountبيوريك كام مرة جمّع كل جيل: لو Gen 2 بيزيد كتير في تطبيق بيشتغل فيه مشكلة allocation.
مشاكل الذاكرة الشائعة (في بيئة بتـ GC)
- Leak بالـ references: الـ GC مبيمسحش اللي لسه ممكن توصله. أسباب شائعة:
staticcollections/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 عالية على أكتر من core | heap و thread لكل core، أعلى throughput لكن أعلى استهلاك للـ RAM |
<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).
الـ Span<T> والـ Memory<T>
كتير من الـ allocations في الكود اليومي بتجي من إننا بنقص ونقسم البيانات: Substring و Split و ToArray كلهم بيعملوا نسخة جديدة. الـ Span<T> هو نافذة (view) على جزء من الذاكرة موجودة أصلاً (array أو string أو stack) من غير نسخ.
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.Split اللي كانت هتعمل array + 2 strings.- الـ
stackallocبيحجز على الـ stack وبيتحرر أوتوماتيك لما الميثود تخلص. استخدمه لـ buffers صغيرة (مئات الـ bytes) فقط وإلا خطر Stack Overflow. - الـ
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>)).
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 الـ conversions بين T[] و Span<T>/ReadOnlySpan<T> بقت implicit أكتر، فكتير من الـ overloads (MemoryExtensions) بتشتغل مباشرة على الـ arrays من غير .AsSpan(). لا تحسّن بـ Span قبل ما تقيس: فايدته الحقيقية في الـ hot paths (parsing, protocols, serialization).
أخطاء شائعة وتشخيص
| الخطأ | العَرَض | السبب | الحل |
|---|---|---|---|
Override Equals من غير GetHashCode | عنصر موجود وبـ Contains بيرجّع false، تحذير CS0659 | الـ hash لسه reference-based فبيروح bucket مختلف | اعمل override للاتنين بنفس الحقول، أو استخدم record |
| Key قابل للتعديل في Dictionary/HashSet | entry «اختفت» بعد تعديل property | الـ hash اتغير بعد الإدخال | keys immutable (record/readonly struct/string/int) |
throw ex; | الـ stack trace بيبدأ من الـ catch | بيصفّر الـ trace | throw; أو غلّف مع inner exception |
Catch Exception وتجاهلها (catch {}) | bugs صامتة وبيانات غلط | الخطأ اتبلع من غير تسجيل ولا معالجة | امسك أنواع محددة، سجّل، أو اسمح لها تعدي لفوق |
Multiple enumeration لـ IEnumerable | query بتتنفذ مرتين (DB hit مضاعف) | deferred execution | ToList() مرة واحدة |
Capture لمتغير الـ for في lambda | كل الـ lambdas بترجّع نفس القيمة | متغير واحد مشترك | انسخه لمتغير محلي جوه الـ body |
نسيان -= على event طويل العمر | RAM بيكبر و handlers بتتنفذ على objects قديمة | الـ publisher بيمسك الـ subscriber | unsubscribe في Dispose، أو weak events |
إنشاء IDisposable من غير using | file locked / connection pool exhausted | الـ GC مبيحرّرش الـ handles في الوقت المناسب | using / await using دايماً |
استدعاء GC.Collect() بإيدك | pauses أكبر وأداء أسوأ | بتكسر ضبط الـ GC الذاتي وبترقّي objects قبل أوانها | شيلها وحلّ سبب الـ allocations |
Span<T> في async method | compile error CS4012 | ref struct مينفعش يعيش عبر await | استخدم Memory<T> وخد .Span وقت الحاجة |
إزاي تـ debug؟
- سلوك collections غريب: اطبع
GetHashCode()لعنصرين المفروض متساويين، وراجع إنEqualsوGetHashCodeبيستخدموا نفس الحقول. - Exception مش واضحة: اقرا
InnerExceptionبالتسلسل، وفعّل «break on first-chance exception» في الـ debugger. - RAM بيزيد: خد
dotnet-gcdumpمرتين وقارن أكتر الأنواع نمواً، وشوف مين ماسكها (static/event/cache).
الأداء والمفاضلات
- Collections: اختار حسب العملية الأكتر تكراراً.
List.Containsفي loop = O(n²)، حوّلها لـHashSet. حددcapacityلما تعرف الحجم. للـ lookup ثابت بعد الـ startup جرّبFrozenDictionary. - LINQ: مريح وغالباً كفاية. في الـ hot paths الجوانب: allocation للـ delegates والـ enumerators، وبطء نسبي مقارنة بـ
forمباشر. قيس بـ BenchmarkDotNet قبل ما تستبدله. - Closures: كل capture = allocation. استخدم
staticlambdas والـ local functions في المسارات الساخنة. - Exceptions: غالية في مسار الفشل، فمتعتمدش عليها في الـ flow الطبيعي. استخدم
TryXxx. - GC: التكلفة مرتبطة بعدد الـ allocations ومعدل نجاة الـ objects، مش بحجم الـ heap فقط. قلّل الـ short-lived allocations، وتجنب الـ LOH المتكرر.
- Span/ArrayPool: أكبر فايدة في parsing و protocols. ضيف تعقيد الكود فقط لما القياس يبرر.
| القرار | الاختيار الأبسط | الاختيار الأسرع | متى تنتقل؟ |
|---|---|---|---|
| تقسيم نص | Split / Substring | ReadOnlySpan<char> + slicing | parsing بحجم كبير أو في hot path |
| معالجة sequence | LINQ | for loop على array/span | profiler بيوريك LINQ هو الاختناق |
| buffer مؤقت | new byte[n] | stackalloc (صغير) / ArrayPool (كبير) | allocation rate عالي أو LOH GCs |
Knowledge Check
أهم النقاط
- الـ generics في C# reified: كود مخصص لكل value type (بدون boxing) وكود مشترك للـ reference types. الـ constraints بتفتح لك الأعضاء، والـ variance (
out/in) بس على interfaces/delegates. Dictionary= buckets + entries؛ الـ O(1) متوقف على جودةGetHashCode. لو overrideEqualsلازمGetHashCode، والـ keys تكون immutable.throw;بيحافظ على الـ stack trace. الـ exceptions للحالات الاستثنائية، وTryXxxللمتوقعة.- الـ event هو delegate بحماية؛ الـ publisher بيمسك الـ subscribers، فاعمل unsubscribe.
- الـ lambda بتلتقط المتغير مش قيمته (closure = allocation).
staticlambda بتمنع الـ 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.
قراءة كود
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.
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).
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.
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
مصادر تعليمية ومتقدمة — Third-party & advanced reading
خريطة التغطية: 12 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.