Nullable Types Nullable types enable internal JS++ types to accept null values. 1234int x = 1;// x = null; // ERRORint? y = 1;y = null; // OK Operators JS++ provides three operators for working with nullable types: ?? (safe default operator), ?. (safe navigation operator), and ?= (safe assignment operator). Safe Default Operator The safe default operator can be used for providing an alternative value if a null value is encountered: 12int? x = null;int? y = x ?? 5; // y == 5 Safe Navigation Operator The safe navigation operator is similar to the . operator except it only looks up class members if the object is not null. 1234567891011121314151617181920import System; class Foo{ Foo? maybe() { if (Math.random() > 0.5) { return this; } else { return null; } } void log() { Console.log("Something happened."); }} auto foo = new Foo();foo.maybe()?.log(); In the above code, maybe can return either an instance of the class or null. By using the safe navigation operator (?.), the log method will only be called if the class instance was returned by maybe. Safe Assignment Operator The safe assignment operator can be used to assign a different value if a null value is present: 123456import System; int? x = null;Console.log(x); // nullx ?= 5;Console.log(x); // 5 Casting Nullable types can be stripped away via casting: 1234class Foo {} Foo? foo = new Foo();Foo bar = (Foo) foo; Casting can throw a CastException. Therefore, it is preferred to use the nullable operators instead. If casting is absolutely necessary, it is preferred to perform a check first: 123456789101112131415import System; class Foo {} Foo? foo;if (Math.random() > 0.5) { foo = new Foo();}else { foo = null;} if (foo != null) { // this check makes sure the cast is safe Foo bar = (Foo) foo;} Unlike casting from other types, casting from nullable or existent types will only strip the nullable or existent type. It will not simultaneously allow downcasting. If you desire to downcast, you need to downcast separately. See Also null Share HTML | BBCode | Direct Link