Nullable Reference Types in C#

Nullable Reference Types in C#
‘Nullable reference types’ and ‘Non-nullable reference types’ to allow the compiler to perform
‘static flow analysis’ for purpose of null-safety.
 
class_name variable_name; //’class_name’ is non-nullable reference type
class_name? variable_name; //’class_name?’ is nullable reference type
 
Benefit: The compiler can perform a static analysis to identify where there is a possibility of ‘null’ values and can show warnings; so we can avoid NullReference Exceptions at coding-time itself.
 
By default, all classes and interfaces are ‘non-nullable reference types’. To convert them as ‘nullable reference type’, suffix a question mark (?). Eg: class?
 
Null forgiving operator (!)
  • Suffix your expression (variable or property) with “!” operator to make that expression as “not null”, at compilation time.
  • Developer says to the C# compiler – that, a variable or property is “not null”. But at run time, if it is actually null, it leads to “NullReference Exception” as normal.
  • So use this operator only when you are sure that your expression (variable of property) is NOT null.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply