JetBrains Rider 2024.3 Help

Code inspection: Possible 'System.InvalidOperationException'

Before you cast a variable of a nullable type to its underlying type, you should make sure that the value is not null. In the example below, we have a nullable double x, and the expression (double)x will throw an exception if x is null.

JetBrains Rider suggests checking for null:

public void Method(double? x) { var y = (double)x; Console.WriteLine(y); }
public void Method(double? x) { if (x != null) { var y = (double)x; Console.WriteLine(y); } }

Alternatively, JetBrains Rider can add the assertion that the expression is not null:

public void Method(double? x) { var y = (double)x; Console.WriteLine(x); }
public void Method(double? x) { Debug.Assert(x != null, "x != null"); var y = (double)x; Console.WriteLine(x); }
Last modified: 08 April 2024