C# Features

Last Updated: 12/2/2023

Programming with Null

Checking for Null

Equality Operator

if(url == null) {
	Console.WriteLine("url is null");
}

InEquality Operator

if(url != null) {
	Console.WriteLine("url is not null");
}

is null Operator Pattern Matching

  • . Starting with C# 7.0, you can check whether a value is null using the is null expression.
string? url = null;
if(url is null) {
	Console.WriteLine("url is null");
}

is not null Operator Pattern Matching

  • In C# 9.0, is not null support was added.
string? url = "";
if(url is not null) {
	Console.WriteLine("url is not null");
}

Null Coalescing ??

expression1 ?? expression2
  • if expression1 is not null, its value is the result of the operation and the other expression is not evaluated. If expression1 does evaluate to null, the value of expression2 is the result of the operator.
string? url = "index.html";
string file = url ?? "default.html";

Null Coalescing Assignment ??=

string? url = null;
url ??= "default.html";

Null-Conditional Operator ?.

int? length = (url != null) ? url.Length : null;
int? length = url?.Length;

Null Forgiving/Suppression Operator !

  • You can use the null-forgiving operator when you definitely know that an expression can't be null but the compiler doesn't manage to recognize that.
Person? p = null;
if(IsValid(p))
Console.WriteLine(p!.Name);

public static bool IsValid(Person? p) => p is not null;

Using attribute

Person? p = null;
if(IsValid(p))
Console.WriteLine(p.Name);
public static bool IsValid([NotNullWhen(true)] Person? p) => p is not null;