Skip to content

Nullable Reference Types (NRT)

ekrctb edited this page Jan 15, 2023 · 5 revisions

Nullable reference types (NRT) are enabled by default for this project. Some files are marked #nullable disable to disable null checking.

NRT should be enabled for new files.

Dependency injection considerations

Compiler will complain if a Resolved field of a non-nullable reference type is not initialized in the constructor. However, the field is non-nullable during the lifetime of the Drawable. We use NRT for a such field, and initialize it by null! (null-forgiving operator applied to null).

- #nullable disable
...
        [Resolved]
-        private ISkinSource skin { get; set; }
+        private ISkinSource skin { get; set; } = null!;
...
-            if (skin != null)
+            if (skin.IsNotNull())

However, that pattern introduces nullability false-positives. For example, in a Dispose, a Resolved field may be null because the Drawable can be disposed after failing to load. In that case, use x.IsNotNull() from osu.Framework.Extensions.ObjectExtensions to suppress warning.

Resolved automatically set CanBeNull for a nullable reference type.

-        [Resolved(CanBeNull = true)]
-        private EditorBeatmap editorBeatmap { get; set; }
+        [Resolved]
+        private EditorBeatmap? editorBeatmap { get; set; }

Clone this wiki locally