← العودة إلى الدورة: C# from scratch

Nullability: string?, ?., ?? and week review

الفيديو قريبًا

null means "no value". Its inventor later called it "my billion-dollar mistake", because using a null value as if it existed is the cause of countless bugs: the famous NullReferenceException. Since C# 8 the language helps avoid it with nullable reference types, a feature that is already enabled in new projects. In this lesson you will understand how it works and see the operators that make it easier to work with values that may be missing.

string and string?: the contract

With nullability enabled, a type like string promises it will never be null, while string? warns that it may be. The compiler checks that promise and emits warnings when you have a value that could be null and use it without checking. It does not change how the program runs, but it points exactly where the risk is. Value types such as int or bool do not accept null by default; if you need a number that "may not exist", use int?, which internally is a Nullable<int> with the properties HasValue and Value. That type is different from string?, even though it is written the same way.

csharp
string name = "Ana";              // never null
string? nickname = null;          // may be null

Console.WriteLine(name.Length);   // safe: 3
// Console.WriteLine(nickname.Length); // warning CS8602 and a crash at run time

if (nickname != null)
{
    Console.WriteLine(nickname.Length);   // safe: the compiler knows it is not null
}

int? maybeAge = null;
Console.WriteLine(maybeAge.HasValue);     // False
maybeAge = 30;
Console.WriteLine(maybeAge.Value + 1);    // 31
Console.WriteLine(maybeAge.GetValueOrDefault()); // 30

The operators ?., ?? and ??=

Three operators make working with null comfortable. The null-conditional operator ?. accesses a member only if the object is not null; if it is, the whole expression gives null instead of failing. The null-coalescing operator ?? returns the value on the left, or the one on the right if the left one is null: it is the usual way to give a default value. And ??= assigns only if the variable is null. Combined, ?. and ?? solve most cases: nickname?.Length ?? 0 means "the length of the nickname, or 0 if there is no nickname".

csharp
string? nickname = null;

int length = nickname?.Length ?? 0;
Console.WriteLine(length);                       // 0

string display = nickname ?? "(no nickname)";
Console.WriteLine(display);                      // (no nickname)

nickname ??= "Anita";                            // assigns because it is null
nickname ??= "Other";                            // does nothing now
Console.WriteLine(nickname?.ToUpper());          // ANITA

string?[] values = ["a", null, "ccc"];
foreach (string? v in values)
{
    Console.WriteLine(v?.Length.ToString() ?? "null");   // 1, null, 3
}

// The ! operator promises "trust me, not null". Use it only when you are sure.
string forced = values[0]!;
Console.WriteLine(forced);

The ! operator (null-forgiving) tells the compiler "trust me, this is not null". It silences the warning but does not remove the risk: if you are wrong, the program still fails. Use it very little. A healthy practice is to treat nullability warnings as errors: each one points to a possible failure before a user sees it. This closes the content of week 5; the quiz checks methods, parameters, scope and nullability.

اختبر ما تعلمته

السؤال 1 من 6

What does string? mean with nullability enabled?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →