C# من الصفر (1): أول برنامج، المتغيرات، والأنواع
لو دي أول مرة تكتب C#، ابدأ من هنا: التلات أقسام الجايين بيبنوا الأساس (متغيرات، شروط، loops، collections، methods، أول class) بمثال واحد بيكبر معاك. لو عندك الأساسيات دي، اقفز لقسم «الـ C# والـ CLR ونظام الأنواع» — باقي الدرس بيشرح اللي بيحصل تحت الحاجات دي.
أكواد C# في الأقسام دي لم يتم عمل compile لها في بيئة تجهيز الموسوعة (الـ .NET SDK مش متاح هناك). هي مكتوبة على C# حديث (.NET 8 وأحدث). اكتبها بإيدك وشغّلها — ده جزء من التعلّم، ولو لقيت خطأ فالـ compiler هيقولك مكانه بالظبط.
شغّل أول برنامج
dotnet new console -n FirstSteps
cd FirstSteps
dotnet runالأمر الأول بيعمل فولدر فيه ملفين مهمين: FirstSteps.csproj (إعدادات المشروع) و Program.cs (الكود). افتح Program.cs وامسح اللي فيه واكتب:
Console.WriteLine("Welcome to the grade book");
Console.Write("Student name: ");
string? name = Console.ReadLine(); // string? = "a string, or null if there was no input"
Console.WriteLine($"Hello, {name}!"); // $"..." is string interpolation: {name} is replaced by its valueمفيش class Program ولا static void Main؟ موجودين، لكن الـ compiler بيولّدهم لك. دي اسمها top-level statements: الملف نفسه هو البرنامج، وبيتنفذ من أول سطر لآخر سطر. كل جملة بتنتهي بـ ;، والـ C# حساسة لحالة الحروف: Console غير console.
المتغيرات: اسم + نوع + قيمة
المتغير صندوق له اسم. في C# كل صندوق له نوع ثابت بيحدد إيه اللي ينفع يتحط فيه — وده بيتفحص قبل ما البرنامج يشتغل (compile time)، فأخطاء كتير بتتمسك قبل ما المستخدم يشوفها.
int age = 21; // whole numbers (about ±2 billion)
long population = 8_100_000_000; // bigger whole numbers; _ is just a visual separator
double average = 87.5; // fractional numbers: fast, but NOT exact (0.1 + 0.2 != 0.3)
decimal price = 199.99m; // exact decimal arithmetic: ALWAYS use this for money (note the m suffix)
bool passed = true; // true or false
char grade = 'A'; // ONE character, single quotes
string city = "Cairo"; // text, double quotes
var count = 10; // var = "compiler, work out the type from the right-hand side" -> int
// var x; // error: nothing to infer the type from
// count = "ten"; // error: count is an int forever
const double PassMark = 50.0; // a value that can never change| عايز تخزّن | النوع | ملاحظة |
|---|---|---|
| عدد صحيح (عدّاد، عمر، كمية) | int | لو ممكن يعدّي 2 مليار: long |
| فلوس | decimal | مش double أبدًا — الـ double بيقرّب |
| قياس علمي / متوسط / نسبة | double | سريع، تقريبي |
| نعم/لا | bool | |
| نص | string | immutable: أي «تعديل» بيعمل string جديد |
العمليات والتحويل بين الأنواع
int a = 7, b = 2;
Console.WriteLine(a / b); // 3 <- int / int throws away the fraction!
Console.WriteLine(a / 2.0); // 3.5 <- one double makes the whole division double
Console.WriteLine(a % b); // 1 <- remainder
Console.WriteLine((double)a / b); // 3.5 <- a cast: "treat a as a double here"
string input = "42";
int number = int.Parse(input); // works, but THROWS an exception if input is "abc"
if (int.TryParse(Console.ReadLine(), out int score)) // the safe way: returns false instead of throwing
{
Console.WriteLine($"You typed {score}; doubled it is {score * 2}");
}
else
{
Console.WriteLine("That was not a whole number.");
}
string text = score.ToString(); // anything -> string
Console.WriteLine($"{87.456:F1}"); // 87.5 format: 1 digit after the point
Console.WriteLine($"{1234.5m:C}"); // currency, formatted for the current cultureأشهر مفاجأتين للمبتدئ: 7 / 2 بتدّي 3 مش 3.5 (قسمة أعداد صحيحة)، و int.Parse بتوقّع البرنامج لو المستخدم كتب حروف. أي حاجة جاية من المستخدم أو ملف أو شبكة: استخدم TryParse.
out int score: الـ method بترجّع bool (نجحت ولا لأ) وبتحط الرقم في المتغير score. نمط هتشوفه كتير في .NET.
C# من الصفر (2): الشروط، التكرار، والـ Collections
القرارات
double mark = 73.5;
if (mark >= 85)
{
Console.WriteLine("Excellent");
}
else if (mark >= 50)
{
Console.WriteLine("Passed");
}
else
{
Console.WriteLine("Failed");
}
// == equal != not equal && and || or ! not
bool honours = mark >= 85 && mark <= 100;
// The same decision as a switch EXPRESSION: it produces a value, and the compiler warns if a case is missing
string letter = mark switch
{
>= 85 => "A",
>= 75 => "B",
>= 65 => "C",
>= 50 => "D",
_ => "F" // _ means "anything else"
};
Console.WriteLine($"Grade: {letter}");= للإسناد و == للمقارنة. if (x = 5) مش بيتعمله compile في C# (على عكس C)، فالـ compiler هيمسكها — لكن if (isReady = true) هيعدّي ويبقى دايمًا true. اكتب if (isReady).
التكرار
for (int i = 1; i <= 5; i++) // you need the counter
{
Console.WriteLine($"Attempt {i}");
}
string[] subjects = ["Math", "Physics", "Programming"]; // an array: fixed size
foreach (string subject in subjects) // you need each item, not its position: prefer this
{
Console.WriteLine(subject);
}
int tries = 0;
while (true) // you do not know in advance how many rounds
{
Console.Write("Enter a mark between 0 and 100: ");
if (double.TryParse(Console.ReadLine(), out double m) && m is >= 0 and <= 100)
{
Console.WriteLine($"Accepted after {tries + 1} tries.");
break; // leave the loop
}
tries++;
}الـ Collections: لما متغير واحد مش كفاية
and Dictionary<TKey, TValue>">
double[] fixedMarks = [70, 85.5, 92]; // array: size decided once
Console.WriteLine(fixedMarks[0]); // 70 <- indexes start at 0
Console.WriteLine(fixedMarks.Length); // 3
// fixedMarks[3] = 1; // IndexOutOfRangeException at run time: valid indexes are 0..2
List<double> marks = [70, 85.5]; // List<T>: grows and shrinks — your default collection
marks.Add(92);
marks.Remove(70);
Console.WriteLine(marks.Count); // 2
Console.WriteLine(marks.Average()); // 88.75 (LINQ: needs `using System.Linq;` — on by default in new projects)
Console.WriteLine(marks.Max());
Dictionary<string, double> byStudent = new() // key -> value lookup
{
["Mona"] = 91,
["Omar"] = 67.5
};
byStudent["Sara"] = 78; // add or overwrite
Console.WriteLine(byStudent["Mona"]); // 91
// Console.WriteLine(byStudent["Zed"]); // KeyNotFoundException
if (byStudent.TryGetValue("Zed", out double zedMark)) // the safe lookup
Console.WriteLine(zedMark);
else
Console.WriteLine("No such student.");
foreach (var (student, value) in byStudent) // each entry is a key/value pair
Console.WriteLine($"{student}: {value}");| السؤال | استخدم |
|---|---|
| قائمة عناصر بترتيب، وعددها بيتغير | List<T> |
| عدد ثابت معروف مسبقًا (أيام الأسبوع، matrix) | array T[] |
| «هات القيمة بتاعة المفتاح ده» بسرعة | Dictionary<TKey, TValue> |
| «العنصر ده موجود ولا لأ؟» من غير تكرار | HashSet<T> |
ليه الـ Dictionary أسرع من البحث في List، وإيه معنى <T> بالتفصيل: ده موضوع الـ Generics والـ Collections في Part 2.
C# من الصفر (3): Methods، أول Class، والأخطاء
Methods: اسم لقطعة منطق
لما نفس الحسبة تتكرر، أو لما جزء من الكود يستاهل اسم، حطّه في method. الـ method بتاخد parameters وبترجّع قيمة (أو void لو مش بترجّع حاجة).
double average = Average([70, 85.5, 92]);
Console.WriteLine($"Average {average:F1} -> {ToLetter(average)}");
PrintLine(); // uses the default value
PrintLine('=', 30);
static double Average(List<double> marks) // return type, name, parameters
{
if (marks.Count == 0)
return 0; // guard clause: handle the odd case first, then the main path
double sum = 0;
foreach (double m in marks)
sum += m;
return sum / marks.Count;
}
static string ToLetter(double mark) => mark switch // expression-bodied: one expression, no braces
{
>= 85 => "A", >= 75 => "B", >= 65 => "C", >= 50 => "D", _ => "F"
};
static void PrintLine(char symbol = '-', int width = 20) // void = returns nothing; parameters can have defaults
{
Console.WriteLine(new string(symbol, width));
}أول Class: بيانات وسلوك مع بعض
لحد دلوقتي الطالب عندنا اسم في متغير ودرجات في متغير تاني. الـ class بيجمعهم في نوع واحد جديد إنت اللي بتعرّفه، ومعاهم العمليات اللي ليها معنى عليهم.
public class Student
{
private readonly List<double> _marks = []; // private: only code inside this class can touch it
public Student(string name) // constructor: runs when you write `new Student(...)`
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("A student needs a name.", nameof(name));
Name = name;
}
public string Name { get; } // property with only a getter: set once, in the constructor
public int MarkCount => _marks.Count; // computed property
public double Average => _marks.Count == 0 ? 0 : _marks.Average();
public void AddMark(double mark)
{
if (mark is < 0 or > 100)
throw new ArgumentOutOfRangeException(nameof(mark), mark, "A mark must be between 0 and 100.");
_marks.Add(mark);
}
}var students = new Dictionary<string, Student>(StringComparer.OrdinalIgnoreCase); // "mona" and "Mona" are the same key
while (true)
{
Console.Write("name mark (or 'done'): ");
string? line = Console.ReadLine();
if (line is null || line.Trim() == "done")
break;
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2 || !double.TryParse(parts[1], out double mark))
{
Console.WriteLine("Please type a name, a space, then a number. Example: Mona 87.5");
continue; // skip to the next round of the loop
}
try
{
if (!students.TryGetValue(parts[0], out Student? student))
{
student = new Student(parts[0]);
students[parts[0]] = student;
}
student.AddMark(mark);
}
catch (ArgumentOutOfRangeException ex) // catch the SPECIFIC failure you know how to handle
{
Console.WriteLine($"Rejected: {ex.Message}");
}
}
Console.WriteLine();
foreach (Student s in students.Values.OrderByDescending(s => s.Average))
Console.WriteLine($"{s.Name,-12} {s.MarkCount} mark(s) average {s.Average,6:F1}");ليه _marks private؟ عشان مفيش كود برا الـ class يقدر يحط درجة 500 أو يمسح الليست. الطريق الوحيد لإضافة درجة هو AddMark اللي بتتحقق. ده اسمه encapsulation: الـ object مسؤول عن إن حالته تفضل صحيحة — وهتلاقي شرحه الكامل في قسم الـ Encapsulation بعد شوية.
throw و try/catch: الـ Student ما يعرفش هو شغال في console ولا في web API، فما ينفعش يطبع رسالة. بيرمي exception بيقول «ده غلط»، واللي نادى عليه هو اللي يقرر يعمل إيه. امسك النوع المحدد اللي تعرف تتصرف معاه؛ catch (Exception) العام بيخبّي أخطاء المفروض تشوفها.
للمدخلات المتوقع إنها تغلط (المستخدم كتب حروف): TryParse و if، مش exceptions. الـ exception للحالة اللي المفروض ما تحصلش.
تفاصيل صغيرة: {s.Name,-12} بيحاذي الاسم في 12 خانة ناحية الشمال؛ Student? معناها «ممكن يكون null»، والـ compiler بيتابعها معاك (ده الـ nullable reference types — له قسم في الدرس).
تمارين قبل ما تكمّل
- Beginner: ضيف للبرنامج أمر
listبيطبع كل الطلبة من غير ما يخرج. - Beginner: ضيف في
Studentproperty اسمهاHighestبترجّع أعلى درجة (وخد بالك من حالة مفيش درجات). - Intermediate: خلّي الحد الأقصى للدرجات 5 لكل طالب:
AddMarkترميInvalidOperationExceptionلو اتعدّى، والبرنامج يمسكها ويطبع رسالة واضحة. - Intermediate: اطبع في الآخر عدد الناجحين (متوسط ≥ 50) ونسبتهم — وخد بالك من قسمة الأعداد الصحيحة.
- Challenge: احفظ البيانات في ملف نصي عند الخروج واقراها عند التشغيل (
File.WriteAllLines/File.ReadAllLines). إيه اللي هيحصل لو الملف مش موجود أو فيه سطر بايظ؟
9 / 2 قسمة أعداد صحيحة = 4، وبعدين 4 * 2.0 = 8 (double). لو عايز 9 اكتب 9 / 2.0 * 2.0.المستخدم هيكتب سعر منتج. أنهي سطر صح؟
decimal (الـ double بيقرّب). ومدخل من مستخدم ⇒ TryParse عشان البرنامج ما يقعش لو كتب نص.student.Marks.Add(500) ويكسر القاعدة. الـ class بيحمي حالته بإنه يخلّي التعديل من خلال methods بتتحقق.الـ C# والـ CLR ونظام الأنواع
الـ C# لغة statically typed: نوع كل متغير بيتحدد وقت الـ compile، والمترجم بيرفض الأخطاء قبل ما الكود يشتغل. والكود اللي بتكتبه مش بيتنفّذ مباشرة؛ بيمر بمرحلتين.
- CTS (Common Type System): العقد اللي بيعرّف الأنواع (class, struct, interface, enum, delegate) وبيخلّي لغات .NET المختلفة تتفاهم. كلمات C# زي
intوstringمجرد أسماء بديلة لأنواع الـ BCL (System.Int32وSystem.String). - Assembly: وحدة النشر (dll أو exe) فيها الـ IL والـ metadata.
- Top-level statements: من C# 9 مش لازم تكتب
class ProgramوMainفي ملف الدخول؛ المترجم بيولّدهم.
| keyword | النوع في .NET | الحجم | ملاحظة |
|---|---|---|---|
int / long | Int32 / Int64 | 4 / 8 bytes | الـ integer arithmetic بتلف (wrap) عند الـ overflow افتراضياً |
double / float | Double / Single | 8 / 4 | binary floating point: مش دقيق للكسور العشرية |
decimal | Decimal | 16 | base-10: للفلوس. أبطأ من double |
bool / char | Boolean / Char | 1 / 2 | char هو UTF-16 code unit مش «حرف» دايماً |
string | String | reference | immutable (هنرجعله في قسم الـ Strings) |
object | Object | reference | جذر كل الأنواع |
int count = 42; // Int32
long big = 3_000_000_000L; // digit separators; 'L' suffix = long
double d = 0.1 + 0.2; // binary floating point
decimal m = 0.1m + 0.2m; // base-10 floating point (money)
bool flag = true;
char letter = 'A'; // one UTF-16 code unit
string name = "Ahmed";
var inferred = 3.5; // 'var' = compiler infers double. Still statically typed!
Console.WriteLine($"{count} {big} {flag} {letter} {name} {inferred.GetType()}");
Console.WriteLine(d == 0.3); // False: 0.1 and 0.2 have no exact binary form
Console.WriteLine(m == 0.3m); // True
Console.WriteLine(7 / 2); // 3 integer division truncates
Console.WriteLine(7 / 2.0); // 3.5 one operand is double
int max = int.MaxValue;
Console.WriteLine(unchecked(max + 1)); // -2147483648 (wraps around silently)
try { Console.WriteLine(checked(max + 1)); } // checked context throws instead
catch (OverflowException) { Console.WriteLine("overflow detected"); }الشرح وتتبّع التنفيذ
- مفيش
Main: المترجم بيولّدProgram.Mainويحط الجمل دي جواه. التنفيذ بيبدأ من أول سطر. varمش «dynamic»: النوعdoubleاتحدد وقت الـ compile، وناتجGetType()هوSystem.Double. استخدمه لما النوع واضح من الطرف اليمين.0.1 + 0.2 == 0.3بـfalseلأن 0.1 مش ممكن يتمثّل بدقة في الـ binary (زي 1/3 في العشري). لهذا للفلوس استخدم decimal، ولمقارنة double استخدم tolerance.int.MaxValue + 1بيرجع قيمة سالبة في السياق الافتراضي (unchecked) عشان الأداء. لو الـ overflow خطر (حسابات مالية، أطوال) استخدمcheckedأو فعّل<CheckForOverflowUnderflow>في الـ csproj.- الناتج المتوقع بالترتيب:
42 3000000000 True A Ahmed System.DoubleثمFalse,True,3,3.5,-2147483648,overflow detected.
const قيمة معروفة وقت الـ compile ومتحطوطة (inlined) في كل مكان بتتستخدم فيه، فلو غيّرتها في library لازم تعيد compile كل اللي بيستخدمها. readonly field بتتحدد وقت التشغيل (في constructor)، وأأمن للقيم اللي ممكن تتغيّر بين الإصدارات.
Value Types مقابل Reference Types
ده أهم تمييز في النظام كله. السؤال: «لما أعمل b = a، إيه اللي بيتنسخ؟»
Value Type (struct, enum, int, bool, DateTime)
المتغير بيحتوي القيمة نفسها. التعيين والتمرير كـ argument بينسخوا القيمة كلها، فالنسختين مستقلتين.
Reference Type (class, interface, delegate, string, array)
المتغير بيحتوي مرجع (reference) لـ object على الـ heap. التعيين بينسخ المرجع بس، فالاتنين بيشاوروا على نفس الـ object.
PointStruct s1 = new(1, 2);
PointStruct s2 = s1; // copies the whole value
s2.X = 99;
Console.WriteLine(s1.X); // 1 - s1 unaffected
PointClass c1 = new(1, 2);
PointClass c2 = c1; // copies only the reference
c2.X = 99;
Console.WriteLine(c1.X); // 99 - same object
// A reference is passed BY VALUE: the callee gets a copy of the reference.
static void Reset(PointClass p)
{
p.X = 0; // follows the copy of the reference -> mutates the shared object
p = new PointClass(5, 5); // rebinds only the local copy; the caller does not see this
}
static void ResetRef(ref PointClass p)
{
p = new PointClass(5, 5); // 'ref' passes the variable itself, so the caller's variable changes
}
Reset(c1);
Console.WriteLine(c1.X); // 0 - mutation visible, rebinding not
ResetRef(ref c1);
Console.WriteLine(c1.X); // 5 - the caller's variable now points to the new object
struct PointStruct { public int X, Y; public PointStruct(int x, int y) { X = x; Y = y; } }
class PointClass { public int X, Y; public PointClass(int x, int y) { X = x; Y = y; } }الشرح
- سطر
s2 = s1بينسخ 8 bytes (حقلين int). تعديلs2.Xمفيش له تأثير على s1. - سطر
c2 = c1بينسخ المرجع بس؛ فيه object واحد، ولما عدّلناc2.Xشفنا التعديل منc1. - في
Reset: الـpنسخة من المرجع.p.X = 0بيغيّر الـ object المشترك (فبيتشاف برا). لكنp = new ...بيغيّر النسخة المحلية بس. ده بيوضح إن «C# بيمرّر كل حاجة by value» وإن الـ value ممكن تكون مرجع. refبيمرّر المتغير نفسه، فتعيينpجواه بيغيّر متغير المُنادي.
فين بتتخزّن القيم؟
الشائع «value types على الـ stack و reference types على الـ heap» تبسيط. الصح: متغير value type بيخزّن بياناته حيث ما هو معرّف. لو local variable فغالباً على الـ stack (أو في register)، لكن لو هو حقل جوه class فهو جزء من الـ object على الـ heap، ولو اتلقط في lambda أو async method بيتنقل للـ heap. أما الـ reference types فالـ object دايماً على الـ heap (والمرجع نفسه قيمة 8 bytes). الفرق العملي اللي يهمّك هو الـ copy semantics وتكلفة الـ allocation والـ GC.
Boxing و Unboxing
لما تحط value type في متغير object أو interface، الـ runtime بيعمل box: بيحجز object على الـ heap وبينسخ القيمة فيه. ده allocation حقيقي بيضغط على الـ GC.
int n = 42;
object boxed = n; // BOXING: heap allocation + copy of 42
n = 100;
Console.WriteLine(boxed); // 42 the box did not change
int back = (int)boxed; // UNBOXING: type check, then copy out
Console.WriteLine(back); // 42
try { long wrong = (long)boxed; } // the box holds an Int32, not an Int64
catch (InvalidCastException) { Console.WriteLine("unbox must match the exact type"); }
IComparable c = n; // hidden boxing: assigning a struct to an interface variableأماكن الـ boxing المخفية: تمرير struct لـ parameter من نوع object، أو استدعاء ToString()/interface method على struct مش بيطبّقها صح، أو الـ collections القديمة (ArrayList). الـ generics (List<int>) بتحل المشكلة (قسم الـ Generics في الجزء 2).
إمتى struct؟
القاعدة التقليدية من Framework Design Guidelines: تجنّب الـ struct إلا لو النوع بيمثّل قيمة واحدة منطقياً زي الأرقام، وحجمه أقل من حوالي 16 byte، وimmutable، ومش هيتعمله boxing كتير. غير كده استخدم class. لو struct كبير لازم تمرره بـ in أو ref readonly عشان تتجنب النسخ، وعلّم النوع readonly struct عشان المترجم ميعملش «defensive copies» لما تنادي عليه عن طريق in.
الـ Classes والـ Objects
الـ class هو القالب (state + behavior)، والـ object هو instance منه على الـ heap. العناصر: fields (البيانات الخام)، properties (واجهة محكومة للبيانات)، methods، constructors، وstatic members (بتخص النوع نفسه مش instance).
public class BankAccount
{
private static int _nextId = 1000; // static: one copy shared by ALL instances
private decimal _balance; // instance field, hidden from outside
public int Id { get; } // get-only auto-property: assignable only in the constructor
public string Owner { get; }
public decimal Balance => _balance; // expression-bodied read-only property
public BankAccount(string owner, decimal openingBalance = 0m)
{
ArgumentException.ThrowIfNullOrWhiteSpace(owner);
ArgumentOutOfRangeException.ThrowIfNegative(openingBalance);
Id = ++_nextId;
Owner = owner;
_balance = openingBalance;
}
public void Deposit(decimal amount)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
_balance += amount;
}
public bool TryWithdraw(decimal amount)
{
if (amount <= 0 || amount > _balance) return false; // business rule enforced HERE
_balance -= amount;
return true;
}
public override string ToString() => $"#{Id} {Owner}: {_balance:N2}";
}
// ---- Program.cs (usage) ----
var acc = new BankAccount("Mona", 500m);
acc.Deposit(250m);
Console.WriteLine(acc.TryWithdraw(1000m)); // False (insufficient funds)
Console.WriteLine(acc); // #1001 Mona: 750.00الشرح وتتبّع التنفيذ
new BankAccount("Mona", 500m): الـ runtime بيحجز object على الـ heap بحقوله على الـ default، بعدين بينفّذ الـ constructor. الـ guard clauses في الأول بترفض البيانات الغلط قبل ما الـ object يتكوّن (مفيش object نص مبني).++_nextIdبيزوّد العداد المشترك ويرجع 1001، فـId = 1001.- الـ
_balanceprivate، والـBalanceللقراءة بس. الطريقة الوحيدة لتغيير الرصيد هيDeposit/TryWithdrawاللي بيحافظوا على الـ invariant «الرصيد مش بيبقى سالب». ده Encapsulation الحقيقي: الحماية للـ invariants مش مجرد إخفاء الحقول. - الناتج: 500 + 250 = 750، السحب 1000 مرفوض فـ
False.
| Modifier | الرؤية |
|---|---|
public | أي كود |
private | جوه النوع نفسه فقط (الافتراضي لأعضاء الـ class) |
protected | النوع والأنواع المشتقة منه |
internal | نفس الـ assembly (الافتراضي للأنواع غير المتداخلة) |
protected internal / private protected | اتحاد / تقاطع protected و internal |
file (C# 11) | نفس ملف المصدر فقط |
قاعدة: ابدأ بأضيق visibility ممكنة ووسّعها عند الحاجة. وبراهن إن static state القابل للتغيير (زي _nextId هنا) مش thread-safe؛ في تطبيق متعدد الـ threads استخدم Interlocked.Increment (هنشرحه في الجزء 3).
Encapsulation و Inheritance و Polymorphism و Abstraction
Encapsulation
إخفاء الحالة الداخلية وإتاحتها عبر واجهة بتحمي الـ invariants (شفنا في BankAccount).
Inheritance
علاقة «is-a»: النوع المشتق بياخد أعضاء الأساس ويضيف أو يعدّل. C# بتدعم وراثة class واحد فقط (وكتير interfaces).
Polymorphism
التعامل مع أنواع مختلفة من خلال نفس الواجهة، والسلوك الفعلي بيتحدد حسب النوع وقت التشغيل.
Abstraction
تعريف «إيه المطلوب» من غير «إزاي» (abstract members و interfaces).
public abstract class Shape
{
public string Name { get; }
protected Shape(string name)
{
Name = name;
Console.WriteLine($"Shape ctor ({name})");
}
public abstract double Area(); // no body: derived MUST implement
public virtual string Describe() => $"{Name} with area {Area():F2}"; // default, may be overridden
}
public sealed class Circle : Shape
{
private readonly double _r;
public Circle(double r) : base("Circle") // base ctor runs FIRST
{
_r = r;
Console.WriteLine("Circle ctor");
}
public override double Area() => Math.PI * _r * _r;
}
public class Rectangle : Shape
{
public double W { get; }
public double H { get; }
public Rectangle(double w, double h) : base("Rectangle") { W = w; H = h; }
public override double Area() => W * H;
public override string Describe() => $"{base.Describe()} ({W}x{H})"; // extend, don't replace
}
// ---- Program.cs (usage) ----
Shape[] shapes = { new Circle(2), new Rectangle(3, 4) };
foreach (Shape s in shapes)
Console.WriteLine(s.Describe());الشرح وتتبّع التنفيذ
Shapeabstract: مينفعشnew Shape(...). الـ constructor بتاعهprotectedعشان المشتقات بس هي اللي تنادي عليه.- أثناء تكوين الـ array:
new Circle(2)⇐ يتنفّذShapector الأول (Shape ctor (Circle)) وبعدين جسمCirclector (Circle ctor). بعدهاnew Rectangle(3,4)⇐Shape ctor (Rectangle). الأساس بيتبني قبل المشتق دايماً. - في الـ foreach: المتغير
sنوعه الثابتShape، لكنs.Describe()بيشغّل النسخة المناسبة للـ object الفعلي. للدائرة:Circle with area 12.57. للمستطيل:Rectangle with area 12.00 (3x4)(استخدمbase.Describe()وأضاف عليه). sealedعلىCircleبيمنع الوراثة منه: بيدّي المترجم والـ JIT فرصة لتحسينات (devirtualization) ويقفل تصميمك للتغيير غير المقصود.
override مقابل new (الفرق اللي بيتسأل عليه في الإنترفيو)
class Base
{
public virtual string Who() => "Base.Who";
public string Hidden() => "Base.Hidden";
}
class Derived : Base
{
public override string Who() => "Derived.Who"; // overrides the virtual slot
public new string Hidden() => "Derived.Hidden"; // hides: a NEW, unrelated method
}
// ---- Program.cs (usage) ----
Base b = new Derived();
Console.WriteLine(b.Who()); // Derived.Who - runtime type decides
Console.WriteLine(b.Hidden()); // Base.Hidden - static type decides
Console.WriteLine(((Derived)b).Hidden()); // Derived.Hiddennew بيكسر الـ polymorphism: نفس الـ object بيدّي نتيجة مختلفة حسب نوع المتغير اللي بتناديه منه. استخدمه نادراً (عادةً لما بتتعامل مع library مش بتتحكم فيها).
في Base() لو نادّيت Who() (virtual)، النسخة المشتقة هتتنفّذ قبل ما constructor المشتق يخلص، يعني حقوله لسه على الـ default (null أو 0). ده مصدر bugs غريبة. ابعد عن ده.
Composition over Inheritance: الوراثة بتربط المشتق بتفاصيل الأساس (fragile base class). لو العلاقة مش «is-a» حقيقية، ركّب الـ object من أجزاء (حقول من نوع interface) بدل ما ترث. ده مرتبط بقوة بمبدأ Liskov Substitution.
الـ Interfaces مقابل الـ Abstract Classes
الاتنين بيعرّفوا عقد من غير تنفيذ كامل، لكن لهم أدوار مختلفة:
| Interface | Abstract class | |
|---|---|---|
| الغرض | «النوع ده بيقدر يعمل X» (capability / contract) | «النوع ده هو نوع من X» ومعاه تنفيذ مشترك |
| الوراثة | الـ class يطبّق أي عدد من الـ interfaces | وراثة class واحد فقط |
| الحالة (fields) | مفيش instance fields | فيه fields و constructors |
| التنفيذ | اختياري عبر default interface methods (C# 8) | أعضاء عادية + abstract |
| تغيير العقد لاحقاً | إضافة member كان بيكسر المطبّقين، الـ default methods خففت ده | إضافة non-abstract member آمن |
| الاستخدام النمطي | الـ DI، الـ mocking في الاختبار، فصل الطبقات | Template Method، كود مشترك لعائلة أنواع |
public record PaymentResult(bool Success, string? TransactionId);
public interface IPaymentGateway
{
string Name { get; }
Task<PaymentResult> ChargeAsync(decimal amount, string currency);
// Default interface method: adds behaviour without breaking existing implementers
string Describe() => $"Gateway: {Name}";
}
public abstract class GatewayBase : IPaymentGateway
{
protected HttpClient Http { get; }
protected GatewayBase(HttpClient http) => Http = http;
public abstract string Name { get; }
// Template Method: shared validation, the variable step is delegated
public async Task<PaymentResult> ChargeAsync(decimal amount, string currency)
{
if (amount <= 0) return new PaymentResult(false, null);
return await SendAsync(amount, currency);
}
protected abstract Task<PaymentResult> SendAsync(decimal amount, string currency);
}
public sealed class StripeGateway : GatewayBase
{
public StripeGateway(HttpClient http) : base(http) { }
public override string Name => "Stripe";
protected override Task<PaymentResult> SendAsync(decimal amount, string currency)
=> Task.FromResult(new PaymentResult(true, Guid.NewGuid().ToString("N"))); // stub for the example
}
// Usage: callers depend on the INTERFACE only
IPaymentGateway gateway = new StripeGateway(new HttpClient());
Console.WriteLine(gateway.Describe()); // Gateway: Stripe
PaymentResult r = await gateway.ChargeAsync(250m, "EGP");
Console.WriteLine(r.Success); // True
// new StripeGateway(...).Describe() would NOT compile: default members are reachable via the interface typeالشرح
- الكود اللي بيستخدم الـ gateway بيعرف
IPaymentGatewayبس، فتقدر تبدّل Stripe بـ PayPal أو fake في الاختبارات بدون ما تلمس المستهلك (ده أساس الـ Dependency Injection). GatewayBaseبيدّي كود مشترك (التحقق من المبلغ) ويسيب خطوة الإرسال للمشتقات (Template Method). ده شيء الـ interface لوحده مش بيقدّمه.- الـ default method
Describeمتاحة عن طريق متغير من نوع interface فقط، مش من متغير نوعه الـ class. - Explicit implementation: لو class طبّق interfaceين فيهم نفس الاسم، تقدر تكتب
string IReader.Read() => ...وstring IWriter.Read() => ...وكل واحد بيتنادى من متغير نوعه الـ interface المقابل بس.
ابدأ بـ interface لأي dependency أو عقد بين طبقات. استخدم abstract class لما يكون فيه كود مشترك وحالة حقيقية بين أنواع متقاربة جداً. ولو الـ abstract class ملوش حالة ولا كود، يبقى هو interface متنكّر.
مبادئ SOLID من زاوية C#
الـ SOLID ليها درس كامل بأمثلة و trade-offs في قسم المعمارية. هنا الربط بالمميزات اللي لسه اتعلمناها بس:
S: Single Responsibility
الـ class ليه سبب واحد للتغيير. مثال: BankAccount بيحمي الرصيد ومش بيبعت إيميلات ولا بيكتب لقاعدة بيانات.
O: Open/Closed
تضيف سلوك جديد بنوع جديد (override/implementation) من غير تعديل الكود الموجود. زي إضافة Triangle : Shape.
L: Liskov Substitution
أي Shape لازم يتحط مكان Shape ويشتغل صح. الـ override اللي بيرمي NotSupportedException علامة إنذار.
I: Interface Segregation
interfaces صغيرة ومركّزة بدل واحدة ضخمة، والـ class بيطبّق اللي محتاجه بس.
D: Dependency Inversion
الكود عالي المستوى بيعتمد على IPaymentGateway مش StripeGateway، والـ constructor injection بيوصّلهم.
الـ Nullable Reference Types
NullReferenceException هي أشهر exception في .NET. الـ Nullable Reference Types (NRT) بتخلّي المترجم يتتبّع «ممكن يكون null ولا لأ» ويحذّرك قبل التشغيل. بتتفعّل في الـ csproj (وهي مفعّلة في القوالب الجديدة):
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable> <!-- reference types are non-null by default -->
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <!-- optional: make null warnings fail the build -->
</PropertyGroup>القاعدة بعد التفعيل: string معناها «مش null أبداً»، و string? معناها «ممكن null». المترجم بيعمل flow analysis: بيتتبع حالة كل متغير (maybe-null أو not-null) بعد كل فحص.
using System.Diagnostics.CodeAnalysis;
public class Customer
{
public required string Name { get; init; } // never null: required forces the caller to set it
public string? MiddleName { get; init; } // may legitimately be null
}
public static class CustomerLogic
{
public static int MiddleLength(Customer c)
{
// return c.MiddleName.Length; // warning CS8602: dereference of a possibly null reference
return c.MiddleName?.Length ?? 0; // null-conditional + null-coalescing
}
public static string Initials(Customer c)
{
if (c.MiddleName is { Length: > 0 } middle) // flow analysis: 'middle' is non-null here
return $"{c.Name[0]}{middle[0]}";
return $"{c.Name[0]}";
}
// [NotNullWhen(true)] tells the compiler: if I return true, 'found' is NOT null
public static bool TryFind(IEnumerable<Customer> all, string name, [NotNullWhen(true)] out Customer? found)
{
found = all.FirstOrDefault(c => c.Name == name);
return found is not null;
}
}
// ---- Program.cs (usage) ----
var list = new List<Customer> { new() { Name = "Mona" } };
if (CustomerLogic.TryFind(list, "Mona", out var cust))
Console.WriteLine(cust.Name); // no warning: cust is known non-null inside the ifالشرح
- الـ
c.MiddleName.Lengthالمباشر بيطلّع تحذير لأن النوعstring?. الحل بيتعمل بـ?.(لو null رجّع null بدل ما يرمي) و??(قيمة بديلة). is { Length: > 0 } middleفحص null وطول في خطوة واحدة، وبعدها المترجم عارف إنmiddleمش null.- الـ
out Customer?بتاعTryFindممكن يكون null، فالمترجم من غير attribute كان هيحذّرك عند استخدامcust.Name. الـ[NotNullWhen(true)]بيعلّمه إن القيمة سليمة لما الدالة ترجّع true. فيه attributes تانية:[MaybeNull],[NotNull],[MemberNotNull]. - في C# 14 ينفع كمان تعيّن بشرط:
customer?.Order = GetCurrentOrder();والطرف اليمين مش بيتنفّذ لوcustomernull.
الـ runtime ما بيعرفش حاجة عن string?. بيانات جاية من JSON أو reflection أو ORM ممكن تكسر الوعد. وعامل الـ ! (null-forgiving) بيطفي التحذير بس من غير ما يتحقق: name!.Length هيرمي NRE لو null. استخدمه بحذر، وفضّل فحص أو required. وعلى حدود النظام (API inputs) لازم تتحقق فعلياً.
التعامل مع الـ Strings وتكلفة الـ Interpolation
الـ string في .NET immutable وبيتخزّن كـ UTF-16. أي «تعديل» بينتج string جديد: بيحجز ذاكرة وينسخ الحروف.
using System.Text;
// BAD: each += allocates a brand-new string and copies everything so far -> O(n^2) copying
string s = "";
for (int i = 0; i < 10_000; i++) s += i;
// GOOD: StringBuilder appends into a growable buffer -> O(n)
var sb = new StringBuilder(capacity: 64_000); // pre-size when you roughly know the length
for (int i = 0; i < 10_000; i++) sb.Append(i);
string result = sb.ToString();
// Joining a sequence: let the library do it
string csv = string.Join(",", new[] { "a", "b", "c" }); // a,b,c
string role = "Admin";
// Comparison: ALWAYS state the comparison explicitly for non-UI text
bool isAdmin = string.Equals(role, "admin", StringComparison.OrdinalIgnoreCase); // fast, culture-independent
// role.ToLower() == "admin" -> allocates, and "I".ToLower() is "ı" under the Turkish culture
// Raw string literal (C# 11): no escaping for quotes or backslashes
string json = """
{ "name": "Mona", "path": "C:\temp" }
""";الشرح
- في الـ loop الأول: الـ string رقم k طوله ~k حرف، فمجموع النسخ ≈ n²/2 حرف و10,000 allocation. مع n كبير ده بيبطّئ ويضغط على الـ GC. الـ
StringBuilderبيزوّد buffer داخلي بس لما يمتلئ. - لكن
a + b + cفي سطر واحد مش مشكلة: المترجم بيحوّله لاستدعاءstring.Concatواحد. المشكلة في الـ loops. - الـ
OrdinalIgnoreCaseبيقارن بالـ code units بدون قواعد ثقافة معيّنة: أسرع وأأمن للمعرّفات والـ headers والأدوار. استخدمCurrentCultureفقط للنص اللي بيظهر للمستخدم. - الـ raw string (
""") ممتاز لـ JSON و SQL و regex لأنه بيتجاهل الـ escaping، وبيقص المسافات الزايدة بناءً على موضع الـ"""الختامي.
تكلفة الـ Interpolation
الـ $"..." مريح، ومن C# 10 بيتترجم لـ DefaultInterpolatedStringHandler بيقلّل الـ allocations والـ boxing مقارنة بـ string.Format القديم. لكنه دايماً بيبني string كاملة فوراً. ده بيسبب مشكلة محددة في الـ logging:
// assume: ILogger logger; int orderId; string userId
// BAD: the string is built even when Information logging is disabled,
// and the output has no structured properties to search/filter by.
logger.LogInformation($"Order {orderId} placed by {userId}");
// GOOD: a constant message template; values become named properties,
// and formatting happens only if the level is enabled.
logger.LogInformation("Order {OrderId} placed by {UserId}", orderId, userId);الـ analyzer CA2254 بيحذّرك من الغلط ده. (الـ logging نفسه هنشرحه في قسم الـ Observability.) ولو شغّال على نصوص كبيرة وعايز تتجنّب Substring اللي بتنسخ، استخدم ReadOnlySpan<char> (الجزء 2).
ملحوظتين سريعتين: الـ string interning معناه إن literals المتطابقة بتشاور على object واحد (ولهذا ReferenceEquals("a","a") بتكون true)، لكن ما تعتمدش عليها؛ استخدم == اللي بتقارن المحتوى. والـ char مش دايماً «حرف»: الإيموجي وبعض الحروف بتحتاج 2 chars (surrogate pair)، فـ "😀".Length == 2.
الـ init و required والـ Immutability
الـ object اللي مش بيتغيّر بعد ما اتبنى (immutable) أسهل في الفهم، وآمن في الـ multi-threading، ومش بيتعمله «تعديل غير متوقع» من كود تاني. C# بتدّيك أدوات:
readonlyللحقول: بتتعيّن في الـ constructor بس.initaccessor: property بتتعيّن في object initializer أو constructor بس، وبعدها قراءة فقط.required(C# 11): المترجم بيجبر المُنشئ يعيّن الـ member وقت الإنشاء.withexpression: نسخة معدّلة من object بدل تعديل الأصلي.
// ---- Product.cs ----
public class Product
{
public required string Sku { get; init; }
public required string Name { get; init; }
public decimal Price { get; init; }
}
public readonly record struct Coords(double X, double Y);
// ---- Program.cs ----
var p = new Product { Sku = "A1", Name = "Pen", Price = 5m }; // OK
// p.Price = 6m; // error CS8852: init-only property cannot be assigned after construction
// var bad = new Product { Sku = "A1" }; // error CS9035: required member 'Name' must be set
// "Change" = create a modified copy (works with records and structs via 'with')
var origin = new Coords(0, 0);
var moved = origin with { X = 3 }; // (3, 0); 'origin' is untouchedتحذير مهم: الـ immutability «سطحية» (shallow). لو الـ property نوعها List<string> فالـ reference ثابت لكن محتوى الـ list لسه ممكن يتغيّر. اعرضها كـ IReadOnlyList<T> أو استخدم ImmutableArray<T> من System.Collections.Immutable. ولو بتبني DTOs فـ required + init تركيبة ممتازة (هنشوفها في درس الـ DTOs).
الـ Records والـ Pattern Matching
Records
الـ record نوع مخصص للبيانات اللي هويتها هي قيمتها. المترجم بيولّد لك: Equals/GetHashCode/== بمقارنة القيم، و ToString مقروء، و Deconstruct، ودعم with. (من توثيق Microsoft: الـ record class بيعتبر object متساويين لو نفس الـ runtime type ونفس قيم الأعضاء.)
// ---- Records.cs ----
public record Address(string City, string Street);
public record Customer(string Name, Address Address, int Age = 0); // positional record
public readonly record struct Money(decimal Amount, string Currency);
// ---- Program.cs ----
var a1 = new Address("Cairo", "Tahrir");
var a2 = new Address("Cairo", "Tahrir");
Console.WriteLine(a1 == a2); // True value equality
Console.WriteLine(ReferenceEquals(a1, a2)); // False still two objects
var c1 = new Customer("Mona", a1, 30);
var c2 = c1 with { Age = 31 }; // copy with one change
Console.WriteLine(c2);
// Customer { Name = Mona, Address = Address { City = Cairo, Street = Tahrir }, Age = 31 }
var (name, address, _) = c1; // Deconstruct (positional records only)
Console.WriteLine($"{name} lives in {address.City}"); // Mona lives in Cairoالشرح
record Customer(string Name, Address Address, int Age = 0)بيعرّف constructor و propertiesinit-only (بنفس الأسماء) تلقائياً. ده فرق عن الـ primary constructor العادي اللي مش بيعمل properties.- مقارنة
a1 == a2بتقارن الأعضاء واحد واحد. وCustomerبيقارنAddressبقيمته كمان (equality متداخلة). withبيعمل نسخة (shallow copy) ويعيّن الخاصية الجديدة. الأصلc1يفضل Age=30.record struct= نفس الفكرة لكن value type (ومعاهreadonlyيخلّيه immutable).
إمتى؟ DTOs، value objects، رسائل/events، نتائج الدوال. إمتى لأ؟ entities لها هوية وحالة بتتغيّر (زي Order في الـ EF Core: بيتتبّع بالـ Id مش بالقيم). وانتبه: لو الـ record فيه عضو reference قابل للتغيير (مثل string[]) فالـ equality بتقارن المرجع، يعني ممكن تلاقي سجلّين «متساويين» وانت بتعدّل الـ array المشترك.
Pattern Matching
الـ patterns بتخليك تفحص شكل البيانات وتستخرج منها قيم في تعبير واحد. الأنواع: type، constant (بما فيها null)، relational (< >=)، logical (and or not)، property، positional، list.
public record DigitalOrder(string DownloadUrl);
public record PhysicalOrder(double WeightKg, string Country);
public static class Shipping
{
public static decimal Cost(object? order) => order switch
{
null => throw new ArgumentNullException(nameof(order)),
DigitalOrder => 0m,
PhysicalOrder { WeightKg: <= 0 } => throw new ArgumentException("weight must be positive"),
PhysicalOrder { WeightKg: <= 1.0, Country: "EG" } => 30m,
PhysicalOrder { WeightKg: <= 5.0, Country: "EG" } => 50m,
PhysicalOrder { Country: not "EG" } p when p.WeightKg > 20 => 400m, // 'when' = extra condition
PhysicalOrder p => 100m + (decimal)p.WeightKg * 10m,
_ => throw new NotSupportedException(order.GetType().Name)
};
public static string Describe(int[] nums) => nums switch
{
[] => "empty",
[var only] => $"one element: {only}",
[1, .., 5] => "starts with 1 and ends with 5",
[_, _, ..] => "two or more elements",
};
}
// ---- Program.cs (usage) ----
Console.WriteLine(Shipping.Cost(new DigitalOrder("x"))); // 0
Console.WriteLine(Shipping.Cost(new PhysicalOrder(0.5, "EG"))); // 30
Console.WriteLine(Shipping.Cost(new PhysicalOrder(3, "EG"))); // 50
Console.WriteLine(Shipping.Cost(new PhysicalOrder(2, "DE"))); // 120
Console.WriteLine(Shipping.Describe([1, 2, 3, 4, 5])); // starts with 1 and ends with 5
if (new object() is string { Length: > 0 } text) Console.WriteLine(text); // 'is' pattern with property testالشرح وتتبّع التنفيذ
- الـ
switchexpression بيجرّب الـ arms بالترتيب وبيرجّع أول واحد يطابق.PhysicalOrder(2,"DE"): يفشل معnull،DigitalOrder،{WeightKg: <= 0}، وفرع"EG"(الدولة DE)، وفرعnot "EG"معwhen p.WeightKg > 20(الوزن 2)، فيوصل للـ arm العام:100 + 2*10 = 120. - ترتيب الـ arms مهم: لو وضعنا
PhysicalOrder pقبل الأخص منها، المترجم هيرفض (الأخص unreachable). والـ arm الأخير_يغطّي كل الأنواع الأخرى، وبدونه المترجم بيحذّر من عدم الاستيفاء (non-exhaustive). - الـ list patterns:
[]فاضي،[var only]عنصر واحد،..slice لأي عدد.[1, .., 5]بيطابق المصفوفة الأولى بتاعتنا. الـ arms التلاتة[]و[var only]و[_, _, ..]بيغطّوا كل الأطوال.
الميزات الحديثة: Primary Constructors و Collection Expressions و C# 14
Primary Constructors (C# 12)
بتحط parameters الـ constructor مباشرة في header الـ class. المهم: دي parameters مش fields ولا properties (إلا في الـ records)، ومتاحة في كل أعضاء الـ class. المترجم بيخزّنها في حقل مخفي فقط لو استخدمتها داخل member. أشهر استخدام: الـ DI.
using Microsoft.Extensions.Logging;
public record Order(int Id);
public interface IOrderRepository { Task<Order?> FindAsync(int id); }
// Before C# 12: private readonly fields + an explicit constructor that assigns them.
// Now: parameters captured directly.
public class OrderService(IOrderRepository repo, ILogger<OrderService> logger)
{
public async Task<Order?> GetAsync(int id)
{
logger.LogInformation("Loading order {OrderId}", id);
return await repo.FindAsync(id);
}
}- الـ parameters قابلة للتعديل (
repo = nullمسموح)، وده ممكن يبقى مصدر bug. لو عايزها ثابتة فحطها فيprivate readonlyfield بنفسك. - لو مرّرت الـ parameter للـ base class واستخدمته كمان في المشتق، المترجم بيحذّر لأنك بتعمل نسخة تانية من القيمة. استخدم property الـ base.
- أي constructor إضافي لازم ينادي الـ primary بـ
: this(...).
Collection Expressions (C# 12)
int[] a = [1, 2, 3];
List<int> b = [4, 5];
int[] all = [.. a, .. b, 6]; // spread: [1, 2, 3, 4, 5, 6]
IEnumerable<string> none = []; // an empty collection of the target type
Span<int> span = [10, 20, 30]; // target-typed: the compiler picks the best creation strategy
Console.WriteLine(string.Join(",", all)); // 1,2,3,4,5,6نفس الصيغة [ ] بتشتغل مع arrays و List<T> و Span<T> والـ interfaces الشائعة والأنواع اللي فيها [CollectionBuilder]. النوع بيتحدد من السياق (target-typed). الـ .. بينسخ عناصر أي sequence جوه. ملحوظة: مع IEnumerable<T> النتيجة collection جاهزة مش lazy.
مميزات C# 14 (مع .NET 10)
public class Person
{
// 'field' keyword: the compiler generates the backing field; you reference it as 'field'
public string Name
{
get;
set => field = value?.Trim() ?? throw new ArgumentNullException(nameof(value));
} = "";
}
public static class StringExtensions
{
// Extension members: an 'extension' block can declare extension PROPERTIES, not just methods
extension(string text)
{
public bool IsBlank => string.IsNullOrWhiteSpace(text);
public string Truncate(int max) => text.Length <= max ? text : text[..max];
}
}
// ---- Program.cs (usage) ----
var person = new Person { Name = " Mona " };
Console.WriteLine($"[{person.Name}]"); // [Mona]
Console.WriteLine(" ".IsBlank); // True
Console.WriteLine("abcdef".Truncate(3)); // abc
Person? maybe = null;
maybe?.Name = "x"; // null-conditional assignment: skipped because maybe is nullالشرح
field: بدل ما تعمل حقل_nameمنفصل عشان تضيف تحقق أو تنضيف في الـ setter، المترجم بيولّد الحقل وانت بتوصله بالكلمةfield. لو عندك عضو اسمهfieldفعلاً استخدم@field.- Extension members: الـ
extension(string text)block بيعرّف المستقبِل مرة واحدة، وتحته properties و methods. الـ" ".IsBlankبيتكتب كأنها property عادية. الصيغة القديمةthis string textلسه شغالة. - Null-conditional assignment:
maybe?.Name = "x"معناها: لوmaybeمش null اعمل التعيين، وإلا تجاهل الطرف اليمين كله (من غير ما يتقيّم). - كلمة تحذير: دي ميزات C# 14، بتحتاج SDK بتاع .NET 10 و LangVersion مناسب. الإصدارات الأقدم هتديك أخطاء compile.
فيه كمان في C# 14: implicit conversions بين Span<T> و ReadOnlySpan<T> والمصفوفات، nameof(List<>) لأنواع generic غير مغلقة، parameters في الـ lambda بـ modifiers من غير ما تكتب النوع ((text, out result) => ...)، وتحميل compound assignment operators (+=) بشكل مخصص.
الـ Operator Overloading والـ Conversions
بتخليك تكتب a + b أو a < b لنوعك الخاص. استخدمها فقط للأنواع «القيمية» (value-like) اللي المعنى الرياضي بتاعها واضح (Money، Vector، Duration)، مش لحاجات بتتفاجئ بيها.
public readonly struct Money : IEquatable<Money>, IComparable<Money>
{
public decimal Amount { get; }
public string Currency { get; }
public Money(decimal amount, string currency)
{
Amount = amount;
Currency = currency;
}
// Arithmetic: only meaningful between the same currency
public static Money operator +(Money a, Money b) { EnsureSame(a, b); return new(a.Amount + b.Amount, a.Currency); }
public static Money operator -(Money a, Money b) { EnsureSame(a, b); return new(a.Amount - b.Amount, a.Currency); }
public static Money operator *(Money a, decimal factor) => new(a.Amount * factor, a.Currency);
// Equality operators MUST come with Equals + GetHashCode, and relational ones come in pairs
public static bool operator ==(Money a, Money b) => a.Equals(b);
public static bool operator !=(Money a, Money b) => !a.Equals(b);
public static bool operator <(Money a, Money b) => a.CompareTo(b) < 0;
public static bool operator >(Money a, Money b) => a.CompareTo(b) > 0;
public static bool operator <=(Money a, Money b) => a.CompareTo(b) <= 0;
public static bool operator >=(Money a, Money b) => a.CompareTo(b) >= 0;
// Conversion: explicit because it throws away the currency (information loss)
public static explicit operator decimal(Money m) => m.Amount;
public bool Equals(Money other) => Amount == other.Amount && Currency == other.Currency;
public override bool Equals(object? obj) => obj is Money m && Equals(m);
public override int GetHashCode() => HashCode.Combine(Amount, Currency);
public int CompareTo(Money other) { EnsureSame(this, other); return Amount.CompareTo(other.Amount); }
public override string ToString() => $"{Amount:N2} {Currency}";
private static void EnsureSame(Money a, Money b)
{
if (a.Currency != b.Currency)
throw new InvalidOperationException($"Currency mismatch: {a.Currency} vs {b.Currency}");
}
}
// ---- Program.cs (usage) ----
var price = new Money(100m, "EGP");
var tax = new Money(14m, "EGP");
Console.WriteLine(price + tax); // 114.00 EGP
Console.WriteLine(price > tax); // True
decimal raw = (decimal)price; // explicit cast required: 100
// price + new Money(5m, "USD"); // throws InvalidOperationException (currency mismatch)الشرح
- الـ operators دوال
staticبكلمةoperator.price + taxبيتترجم لاستدعاءMoney.op_Addition(price, tax). - لو عرّفت
==لازم تعرّف!=، ولازم تـ override الـEquals(object)وGetHashCodeبشكل متسق، وإلا الـ Dictionary والـ HashSet هيتصرّفوا غلط (هنشرحه بالتفصيل في «Equality and GetHashCode» في الجزء 2). وكذلك< >و<= >=بيتعرّفوا أزواج. - implicit مقابل explicit:
implicitلتحويل مضمون وآمن بدون فقد معلومات (int → long).explicitلو ممكن يفقد معلومات أو يرمي exception، فبيتطلب cast صريح عشان القارئ يشوف الخطورة. - لو مش محتاج التحكم اليدوي:
public readonly record struct Money(decimal Amount, string Currency)بيدّيك equality و ToString مجاناً، وبتضيف بس الـ operators اللي محتاجها.
أخطاء شائعة وتشخيص
| الغلطة | المشكلة | الإصلاح |
|---|---|---|
Mutable struct بيتعدّل جوه List<T> أو foreach | list[0].X = 5 بيعدّل نسخة مؤقتة (المترجم بيمنعها)، و foreach variable نسخة | خلّي الـ struct readonly، أو استخدم class، أو استبدل العنصر بنسخة جديدة |
Boxing في hot path (تمرير struct كـ object/interface) | allocation لكل نداء وضغط على الـ GC | generics، أو IEquatable<T>، وراجع بـ profiler/BenchmarkDotNet |
استخدام new بدل override | نتيجة مختلفة حسب نوع المتغير، الـ polymorphism بيكسر | virtual في الأساس و override في المشتق |
| نداء virtual method من constructor | المشتق بيتنفّذ قبل ما حقوله تتهيّأ | اقفل الـ class (sealed) أو أجّل التهيئة لـ method منفصلة |
إسكات تحذيرات null بـ ! في كل حتة | NRE وقت التشغيل زي زمان بالظبط | فحص صريح، required، أو تصميم ميسمحش بالـ null |
s += x في loop كبير | O(n²) نسخ وأحمال GC | StringBuilder أو string.Join |
Interpolation داخل logger.Log* | بيبني string دايماً ويفقد الـ structured properties | message template + parameters |
| Record فيه عضو مصفوفة/List قابل للتغيير | المقارنة بالمرجع، فالـ equality مش زي المتوقع | استخدم ImmutableArray أو قارن المحتوى يدوياً |
| Primary constructor parameter متغيّر | القيمة بتتغيّر في النص بدون ما تلاحظ | انسخها لـ readonly field لو عايزها ثابتة |
تعريف == بدون Equals/GetHashCode | الـ HashSet/Dictionary بيدوّروا غلط | طبّق الـ 4 متسقين، أو استخدم record struct |
أي سلوك «غريب» في النسخ ⇐ اسأل: ده value type ولا reference type؟ في الـ debugger شوف لو المتغيرين بيشاوروا على نفس الـ object (Make Object ID في Visual Studio). وفي الأداء: قيس قبل ما تحسّن (BenchmarkDotNet أو dotnet-counters) وراقب الـ allocations.
Knowledge Check
أهم النقاط
- C# ⇐ IL ⇐ JIT. النوع الثابت بيتفحص وقت الـ compile، و
varمشdynamic. decimalللفلوس، وdoubleمش دقيق للكسور العشرية، والـ integer overflow صامت إلا لوchecked.- Value type: المتغير يحتوي القيمة والتعيين ينسخها. Reference type: المتغير يحتوي مرجع والتعيين ينسخ المرجع. كل حاجة تتمرّر by value، و
refبيمرّر المتغير. - Boxing = allocation + نسخ. أي struct في
object/interface بيتعمله box. virtual/override= polymorphism حقيقي حسب النوع الفعلي؛newبيخبّي بس. الأساس بيتبني قبل المشتق.- Interface للعقد والـ DI، abstract class لكود وحالة مشتركة. تفضّل Composition على Inheritance.
- NRT ضمان compile-time؛
!بيسكت التحذير مش بيحل المشكلة. - Records للبيانات ذات الـ value equality؛ pattern matching لفحص الشكل بالترتيب.
- الـ Strings immutable:
StringBuilderفي الـ loops، ومقارناتOrdinal، و message templates في الـ logging.
أسئلة مفاهيمية
C# بتمرر الـ objects by reference؟
لأ. بتمرّر كل حاجة by value. في الـ reference types القيمة اللي بتتنسخ هي المرجع. عشان كده تعديل حالة الـ object بيظهر عند المُنادي لكن تعيين المتغير لـ object جديد مش بيظهر (إلا لو ref).
ليه 0.1 + 0.2 != 0.3 في double، ومع decimal بيشتغل؟
الـ double بيمثّل الأرقام في base-2، والـ 0.1 كسر دوّار فيه، فبيتقرّب. الـ decimal بيمثّل في base-10 فالأرقام العشرية بتتمثّل بدقة. مقابل ده decimal أبطأ وأكبر.
إيه الفرق بين override و new؟
override بيستبدل خانة الـ virtual فالنسخة بتتحدد بالنوع الفعلي. new بيعرّف method جديدة بنفس الاسم بتتحدد بالنوع الثابت للمتغير، فبيكسر الـ polymorphism.
متى تختار interface بدل abstract class؟
لما تكون محتاج عقد بدون حالة أو كود، أو class يطبّق عدة عقود، أو تحتاج mocking/DI. الـ abstract class لما يبقى فيه كود وحالة مشتركة فعلاً.
ليه الـ Nullable Reference Types مش بتمنع NullReferenceException تماماً؟
لأنها تحليل وقت compile، والـ runtime مبيعرفش عنها. البيانات الخارجية (JSON، ORM، reflection) والـ ! ممكن يدخّلوا null.
قراءة كود
إيه ناتج: object o = 7; o = (int)o + 1; long x = (long)o; ؟
o بيحتوي int (8 بعد الجمع ثم boxing جديد). الـ cast (long)o بيرمي InvalidCastException لأن الـ unboxing لازم يطابق النوع بالظبط (int)، ولازم تعمل (long)(int)o.
record P(string[] Tags); var a = new P(arr); var b = new P(arr); arr[0] = "x"; إيه ناتج a == b ؟
true. الـ equality بتقارن Tags بالمرجع (Equals العادية للـ array) وهي نفس المصفوفة قبل وبعد التعديل. المقارنة مبتتأثرش بمحتواها.
أسئلة إنترفيو شائعة
اشرح الفرق بين struct و class ومتى تستخدم كل واحد؟
struct value type بيتنسخ عند التعيين، مناسب لقيم صغيرة immutable (أقل من حوالي 16 byte) ومش بيتعمله boxing كتير. class reference type مناسب للكيانات والأحجام الكبيرة وأي حاجة ليها هوية أو حالة بتتغيّر.
إيه بيحصل في الذاكرة لما تعمل boxing؟ وإزاي تتجنبه؟
بيتحجز object على الـ heap فيه نسخة من القيمة (مع header)، والمتغير بيشاور عليه. بنتجنبه بالـ generics (List<int>)، وتطبيق IEquatable<T>، وتجنّب تمرير struct كـ object.
ليه نستخدم records بدل classes للـ DTOs؟ وإمتى لأ؟
الـ value equality والـ with و ToString/Deconstruct مجاناً وبشكل immutable تلقائي. لا للـ entities اللي ليها هوية وحالة بتتغيّر وبيتتبّعها EF بالـ Id.
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
مصادر تعليمية ومتقدمة — Third-party & advanced reading
خريطة التغطية: 12 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.