ReSharper 2017.2 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.

ReSharper suggests checking for null:

Suboptimal codeAfter the quick-fix
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, ReSharper can add the assertion that the expression is not null:

Suboptimal codeAfter the quick-fix
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: 11 December 2017

See Also