
ليه الـ nullable reference types مش هتمنع الـ null وقت التشغيل؟
- كاتب موثّق
- .NET 10
محتويات المقال
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? بس هو اللي يقدر.
string، ولو استخدمت string? من غير ما تتشيك عليه، ولو constructor ساب property مش nullable من غير قيمة. والكود اللي مفيهوش nullable warnings خالص فعلًا فيه null bugs أقل بكتير. وكمان الشكل شبه int وint?، واللي فيه int فعلًا مستحيل يبقى null. الفرق إن int? نوع تاني خالص وقت التشغيل اسمه Nullable<int>، أما string? فلأ.
اللي بيحصل فعلًا
علامة الـ ? مش نوع
? مش نوعstring والـ string? الاتنين System.String. الـ ? بيسجّل نيتك عشان الـ بتاع الـ compiler يعرف أنهي expressions حالتها not-null وأنهي maybe-null. ومفيش أي check بيتولّد لما قيمة تتحط في متغير أو تتبعت لـ method. الـ null بيتنقل براحته لحد ما حاجة تستخدمه، وساعتها بس بيرمي exception.
التحليل شايف الكود اللي بيعمله compile بس
الـ 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 disable أو NoWarn، والكود ده بيفضل من غير check لحد ما حد يرجّعها تاني. والـ nullable attributes زي [NotNullWhen] و[MemberNotNull] مش بتغيّر ده. بتدّي التحليل معلومات أكتر، لكن بكلام الـ docs، مش بتضيف أي checks على الـ implementation بتاعك.
الـ request بتاع الـ partner قبل وبعد
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);using System.Text.Json;var options = new JsonSerializerOptions{ RespectNullableAnnotations = true, // "Email": null throws RespectRequiredConstructorParameters = true, // a missing Email throws};var json = """{"CustomerId":"c-42"}""";try{ JsonSerializer.Deserialize<CreateOrder>(json, options);}catch (JsonException){ Console.WriteLine("400 Bad Request: Email is required"); // fails early}public record CreateOrder(string CustomerId, string Email);string هي null. ومن أول .NET 9 فيه اتنين options اختياريين بيقفلوا الباب ده: الـ RespectNullableAnnotations بيرفض null صريح لـ property أو parameter مش nullable، والـ RespectRequiredConstructorParameters بيرفض الـ constructor parameter الناقص. والـ Microsoft بتنصح بالاتنين لأي application جديد. دلوقتي الـ request الغلط بيفشل على الحدود، برسالة فيها اسم الحقل، بدل ما يفشل جوه service بعيدة.
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 وقتها |
! بيتشيك على الـ null | |
تطبقها إزاي في مشروعك
حوّل الـ nullable warnings لـ errors ضيف <WarningsAsErrors>nullable</WarningsAsErrors>عشان الوعد بتاع وقت الـ compile يفضل كامل والكود بيتغير.اعمل validation على كل الحدود فعّل RespectNullableAnnotationsوRespectRequiredConstructorParametersفي الـ JSON options، وعلّم الـ properties الإجبارية بـrequired، واعمل validation للـ request models قبل ما توصل للـ business logic.احمي الـ public entry points في الـ libraries والـ services المشتركة، نادي ArgumentNullException.ThrowIfNullأوArgumentException.ThrowIfNullOrWhiteSpaceعلى الـ parameters اللي ممكن يوصلها callers برّه الـ nullable context بتاعك.راجع كل ! وكل 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، طالما انت عارف أنهي أبواب مش بتقفلها.
📚 المصادر
Nullable reference types (C#) — Microsoft Learn Nullable migration strategies (C#) — Microsoft Learn Attributes for nullable static analysis (C# reference) — Microsoft Learn Respect nullable annotations (System.Text.Json) — Microsoft Learn Require properties for deserialization (System.Text.Json) — Microsoft Learn
التعليقات (0)