الانتقال إلى المحتوى
.NETC#· 8 دقائق للقراءة

ليه الـ nullable reference types مش هتمنع الـ null وقت التشغيل؟

الفرق بين string و string? وعد وقت الـ compile، مش check وقت التشغيل. الـ null لسه بيدخل منين، وتقفل الأبواب دي إزاي.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

فيه order API عنده public record CreateOrder(string CustomerId, string Email);، والـ nullable reference types شغالة، والـ build مفيهوش ولا warning. وفيه partner integration بعت request من غير حقل الإيميل. الـ JSON deserializer بنى الـ record عادي، وبعدها بكام نداء order.Email.ToLowerInvariant() رمى NullReferenceException جوه الـ notification service، في سطر الـ compiler كان قايل عليه آمن. والـ 500 ظهر في الـ logs بتاعة الـ partner، مش على حدود الـ API اللي كان ممكن يترفض عندها الـ request بـ 400 واضح.

الفكرة الغلط الشائعة

الفكرة بتقول: أول ما تفعّل <Nullable>enable</Nullable>، المتغير اللي متعرّف string عمره ما هيشيل null وقت التشغيل، والـ string? بس هو اللي يقدر.

وهي فكرة مفهومة، لأن الـ feature دي شاطرة في شغلها. الـ compiler بيحذّرك لو حطيت null في string، ولو استخدمت string? من غير ما تتشيك عليه، ولو constructor ساب property مش nullable من غير قيمة. والكود اللي مفيهوش nullable warnings خالص فعلًا فيه null bugs أقل بكتير. وكمان الشكل شبه int وint?، واللي فيه int فعلًا مستحيل يبقى null. الفرق إن int? نوع تاني خالص وقت التشغيل اسمه Nullable<int>، أما string? فلأ.

اللي بيحصل فعلًا

علامة الـ ? مش نوع

الـ docs بتاعة Microsoft صريحة: سلوك البرنامج وقت التشغيل مش بيتغير، والـ nullable reference types حاجة بتاعة وقت الـ compile بالكامل. الـ string والـ string? الاتنين System.String. الـ ? بيسجّل نيتك عشان الـ بتاع الـ compiler يعرف أنهي expressions حالتها not-null وأنهي maybe-null. ومفيش أي check بيتولّد لما قيمة تتحط في متغير أو تتبعت لـ method. الـ null بيتنقل براحته لحد ما حاجة تستخدمه، وساعتها بس بيرمي exception.

التحليل شايف الكود اللي بيعمله compile بس

الـ compiler بيفكّر في الـ source code بتاعك. وأي حاجة بتعمل objects وقت التشغيل، أو اتعملها compile من غير الـ annotations بتاعتك، برّه مجال رؤيته. ومن هنا الـ nulls بتدخل:

  • الـ deserializers والـ mappers: بيبنوا الـ objects من خلال الـ constructors والـ setters وقت التشغيل، فالـ null اللي في الـ JSON أو الحقل الناقص بيبقى null في property مش nullable من غير ولا warning.
  • الكود الـ oblivious: الكود اللي اتعمله compile والـ nullable مقفول، زي الـ libraries القديمة والملفات الـ generated، اسمه nullable-oblivious. يقدر يبعت null للـ parameter اللي نوعه string عندك، والـ compiler مش هيحذّر من النداء ده.
  • الـ : الـ name!.Length والـ = null! بيقولوا للـ compiler ما يقلقش. والـ docs بتعتبر كل واحدة فيهم مكان الـ compiler مبقاش يقدر يحميك فيه.
  • ثغرات معروفة: الـ new string[3] بيعمل تلات عناصر null، والـ default بتاع struct بيسيب الـ reference fields اللي مش nullable بـ null. ولا واحدة فيهم بتطلّع warning.

warnings مش errors

الـ nullable diagnostics عبارة عن warnings، فالمشروع اللي مليان منها لسه بيعمل build وبيتعمله deploy. ووقت الـ migration كمان الفرق بتقفلها بـ #nullable disable أو NoWarn، والكود ده بيفضل من غير check لحد ما حد يرجّعها تاني. والـ nullable attributes زي [NotNullWhen] و[MemberNotNull] مش بتغيّر ده. بتدّي التحليل معلومات أكتر، لكن بكلام الـ docs، مش بتضيف أي checks على الـ implementation بتاعك.

الـ request بتاع الـ partner قبل وبعد

التاب الأول بيثق في الـ annotations. والتاني بيطلب من System.Text.Json يفرضها على الحدود:

C# Program.cs
using System.Text.Json;var json = """{"CustomerId":"c-42"}""";     // the partner forgot Emailvar order = JsonSerializer.Deserialize<CreateOrder>(json)    ?? throw new JsonException("Empty body");// No warning: Email is a non-nullable string, but it holds nullConsole.WriteLine(order.Email.ToLowerInvariant()); // NullReferenceExceptionpublic record CreateOrder(string CustomerId, string Email);

بشكل افتراضي، الـ System.Text.Json بيعامل كل parameters الـ constructor على إنها optional، واللي ناقص بيحط مكانه القيمة الافتراضية، واللي في حالة string هي null. ومن أول .NET 9 فيه اتنين options اختياريين بيقفلوا الباب ده: الـ RespectNullableAnnotations بيرفض null صريح لـ property أو parameter مش nullable، والـ RespectRequiredConstructorParameters بيرفض الـ constructor parameter الناقص. والـ Microsoft بتنصح بالاتنين لأي application جديد. دلوقتي الـ request الغلط بيفشل على الحدود، برسالة فيها اسم الحقل، بدل ما يفشل جوه service بعيدة.

وللكود اللي مش تحت إيدك وبينادي على الكود بتاعك، احمي الـ public entry points بـ checks حقيقية وقت التشغيل:

C# EmailSender.cs
public sealed class EmailSender{    public void Send(string to, string body)    {        // Oblivious callers, or a stray !, can still pass null here        ArgumentException.ThrowIfNullOrWhiteSpace(to);        ArgumentNullException.ThrowIfNull(body);        Console.WriteLine($"Sending {body.Length} chars to {to}");    }}

الفكرة الغلط vs الحقيقة

الفكرة الغلطالحقيقة
الـ string مستحيل يشيل null بعد ما تفعّل الـ nullableالـ string والـ string? نفس النوع وقت التشغيل، ومفيش check وقتها
مفيش warnings يعني مفيش nullsيعني مفيش nulls التحليل يقدر يشوفها في الكود اللي عمله compile
الـ deserializers بتحترم الـ annotationsبس مع options اختيارية، وحتى ساعتها فيه نقط عمياء
الـ operator ! بيتشيك على الـ nullبيسكّت الـ warning وبس، ومفيش كود بيتنفذ
الـ nullable attributes بتضيف checks وقت التشغيلبتدّي التحليل معلومات، والـ implementation بتاعك مش بيتشيك عليه

تطبقها إزاي في مشروعك

  1. حوّل الـ nullable warnings لـ errorsضيف <WarningsAsErrors>nullable</WarningsAsErrors> عشان الوعد بتاع وقت الـ compile يفضل كامل والكود بيتغير.
  2. اعمل validation على كل الحدودفعّل RespectNullableAnnotations وRespectRequiredConstructorParameters في الـ JSON options، وعلّم الـ properties الإجبارية بـ required، واعمل validation للـ request models قبل ما توصل للـ business logic.
  3. احمي الـ public entry pointsفي الـ libraries والـ services المشتركة، نادي ArgumentNullException.ThrowIfNull أو ArgumentException.ThrowIfNullOrWhiteSpace على الـ parameters اللي ممكن يوصلها callers برّه الـ nullable context بتاعك.
  4. راجع كل ! وكل null!دوّر على الـ null-forgiving operator. بدّل كل واحد بـ check حقيقي أو initialization صح أو member عليه required، وسيب بس اللي تقدر تبرره في comment.

الخلاصة

  • الـ nullable reference types حاجة بتاعة وقت الـ compile بس: string وstring? نفس النوع وقت التشغيل.
  • التحليل مش شايف الـ nulls اللي جاية من الـ deserializers أو الـ libraries الـ oblivious أو الـ ! أو الـ arrays الجديدة أو الـ default structs.
  • من أول .NET 9، الـ System.Text.Json يقدر يفرض الـ annotations، بس لما تختار ده بنفسك، وبحدود.
  • اعمل validation للداتا على الحدود، واحمي الـ public APIs بـ ThrowIfNull، وعامل الـ nullable warnings كـ errors.
  • خلّي الـ annotations: بتمنع أغلب الـ null bugs، طالما انت عارف أنهي أبواب مش بتقفلها.

📚 المصادر

  1. Nullable reference types (C#) — Microsoft Learn
  2. Nullable migration strategies (C#) — Microsoft Learn
  3. Attributes for nullable static analysis (C# reference) — Microsoft Learn
  4. Respect nullable annotations (System.Text.Json) — Microsoft Learn
  5. Require properties for deserialization (System.Text.Json) — Microsoft Learn

التعليقات (0)